您的位置:首页 > 编程语言 > Ruby

ruby编程中的异常处理

2016-06-18 04:08 555 查看
1.异常处理的语法

(1)不显式指定异常对象

begin
 可能会发生异常的处理
rescue
 发生异常时的处理
end
(2)显式指定异常对象

begin
 可能会发生异常的处理
rescue => 引用异常对象的变量
 发生异常时的处理
end
举例来说:

ltotal=0 # 行数合计
wtotal=0 # 单词数合计
ctotal=0 # 字数合计
ARGV.each do |file|
begin
input = File.open(file) # 打开文件(A)
l=0 # file 内的行数
w=0 # file 内的单词数
c=0 # file 内的字数
input.each_line do |line|
l += 1
c += line.size
line.sub!(/^\s+/, "") # 删除行首的空白符
ary = line.split(/\s+/) # 用空白符分解
w += ary.size
end
input.close # 关闭文件
printf("%8d %8d %8d %s\n", l, w, c, file) # 整理输出格式
ltotal += l
wtotal += w
ctotal += c
rescue => ex
print ex.message, "\n" # 输出异常信息(B)
end
end

printf("%8d %8d %8d %s\n", ltotal, wtotal, ctotal, "total")
(3)ensure关键字必须执行语句

begin
 有可能发生异常的处理
rescue => 变量
 发生异常后的处理
ensure
 不管是否发生异常都希望执行的处理
end
(4)指定需要捕捉的异常类型

begin
 可能发生异常的处理
rescue Exception1, Exception2 => 变量
 对Exception1 或者Exception2 的处理
rescue Exception3 => 变量
 对Exception3 的处理
rescue
 对上述异常以外的异常的处理
end
举例来说:

file1 = ARGV[0]
file2 = ARGV[1]
begin
io = File.open(file1)
rescue Errno::ENOENT, Errno::EACCES
io = File.open(file2)
end


2.raise语句主动抛出异常

         使用 raise 方法,可以使程序主动抛出异常。在基于自己判定的条件抛出异常,或者把刚捕捉到的异常再次抛出并通知异常的调用者等情况下,我们会使用raise 方法。

raise 方法有以下 4 种调用方式:

(1) raise message

抛出 RuntimeError 异常,并把字符串作为 message 设置给新生成的异常对象。

(2)raise 异常类

抛出指定的异常。

(3)raise 异常类,message

抛出指定的异常,并把字符串作为 message 设置给新生成的异常对象。

(4)raise

在 rescue 外抛出 RuntimeError。在 rescue 中调用时,会再次抛出最后一次发生的异常($!)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: