异常处理 #
创建异常 #
异常使用 Exception
类进行表述。
Exception.new('something wrong')
抛出异常 #
可以使用关键字 raise
抛出异常。
raise Exception.new('something wrong')
异常处理 #
Ruby 异常处理的基本格式为,其中 rescue
可以定义多遍
begin
<code may raise exception>
rescue <exception type>
<handle exception>
else
<executes when there is no exception>
ensure
<executes whatever exception raised>
end
其中 ensure
无论异常是否抛出都会被执行,但是 ensure
无法产生返回值。
例
def str2int(n)
begin
result = Integer(n)
if result == 1
raise Exception.new('something wrong')
end
result
rescue ArgumentError => error
puts error.backtrace
0
rescue Exception
100
ensure
puts 'finally'
300
end
end
执行结果,注意 ensure
无法修改返回值的结果。
puts str2int(10) # => 10
puts str2int('10') # => 10
puts str2int('1a0') # => 0
puts str2int('a10') # => 0
puts str2int('1') # => 100
重试 #
在 rescue
中通常可以改变输入的参数调用 retry
语句以进行条件的重试。
def str2int(n)
begin
result = Integer(n)
rescue ArgumentError
n = 67
retry
end
end
puts str2int('a10')
catch…throw #
catch…throw 可以用于中断程序的逻辑,主要用于异常或者循环中。
def promptAndGet(i)
for j in i..20
catch :quit do
throw :quit if j == 3
puts "j is #{j}"
end
end
end