Answers:
方法“ def”可以用作“ begin”语句:
def foo
...
rescue
...
end
do
/ end
块文字形成隐式异常块。
rescue TypeError; rescue NameError
-或用逗号分隔异常类,例如rescue TypeError, NameError
您还可以在线救援:
1 + "str" rescue "EXCEPTION!"
将打印出“ EXCEPTION!” 因为“无法将字符串强制转换为Fixnum”
StandardError
及其所有子类,例如NameError
–意味着即使您的代码中有错字也不会引发错误。。请参阅Thoughtbot.com/blog/don-t-inline-rescue-in-红宝石。
例:
begin
# something which might raise an exception
rescue SomeExceptionClass => some_variable
# code that deals with some exception
ensure
# ensure that this code always runs
end
在这里,def
作为begin
声明:
def
# something which might raise an exception
rescue SomeExceptionClass => some_variable
# code that deals with some exception
ensure
# ensure that this code always runs
end