TL;DR:使用StandardError
代替常规异常捕获.当重新引发原始异常时(例如,当救援仅记录异常时),救援Exception
可能是可以的.
Exception
是Ruby's exception hierarchy的根,所以当你rescue Exception
时,你从everything中解救出来,包括SyntaxError
、LoadError
和Interrupt
这样的子类.
救援Interrupt
可防止用户使用CTRLC退出程序.
救援SignalException
会阻止程序正确响应信号.除非到kill -9
年,否则它将是无法解决的.
拯救SyntaxError
意味着失败的eval
将默默地这样做.
所有这些都可以通过运行此程序,并try 按CTRLC或kill
键来显示:
loop do
begin
sleep 1
eval "djsakru3924r9eiuorwju3498 += 5u84fior8u8t4ruyf8ihiure"
rescue Exception
puts "I refuse to fail or be stopped!"
end
end
从Exception
人中解救出来甚至不是默认情况.做
begin
# iceberg!
rescue
# lifeboats
end
不是从Exception
拯救,而是从StandardError
拯救.通常,您应该指定比默认的StandardError
更具体的内容,但是从Exception
broadens中拯救范围,而不是缩小范围,并且可能会产生灾难性的结果,使错误查找变得极其困难.
如果您确实希望从StandardError
中拯救,并且需要一个变量(例外情况除外),您可以使用以下表格:
begin
# iceberg!
rescue => e
# lifeboats
end
这相当于:
begin
# iceberg!
rescue StandardError => e
# lifeboats
end
在少数几个常见的情况下,从Exception
中拯救是明智的,其中之一是出于日志(log)记录/报告目的,在这种情况下,您应该立即重新提出例外情况:
begin
# iceberg?
rescue Exception => e
# do some logging
raise # not enough lifeboats ;)
end