Ruby的异常处理

Ruby在处理0.1+0.2是会出现精度问题:

  许多语言都有类似问题,详见网址:http://0.30000000000000004.com/

Ruby的异常处理

如果异常处理范围是整个方法体,可以省略begin和end,直接写rescure和ensure部分的程序,不过要写在最后,避免后面的方法体内容被跳过。

def foo
    方法体
rescure => ex
    异常处理
ensure
    后处理
end

范例:


begin
input = File.open("liuyang.txt")
input.each do |line|
printf("%s,%d", line, line.size)
end
input.close
a =1
printf(" %d ", a)
rescue => ex
puts "**************"
puts ex.message #message : 异常信息
puts ex.backtrace #backtrace / $@ : 异常的位置信息
sleep(3)
retry #使用retry后,begin一下的处理会再重新做一遍
ensure
puts "no matter what happened , execute" #不管是否发生异常,这需要执行
end
 
原文地址:https://www.cnblogs.com/liuyang92/p/5894701.html