为什么“救援Exception =>在Ruby中? [英] Why is it bad style to `rescue Exception => e` in Ruby?
问题描述
Ryan Davis的 Ruby QuickRef 说(没有解释):
Ryan Davis’s Ruby QuickRef says (without explanation):
不要抢救异常。 EVER。或者我会刺伤你。
Don’t rescue Exception. EVER. or I will stab you.
为什么不?什么是正确的事情?
Why not? What’s the right thing to do?
推荐答案
异常
是 Ruby的异常层次结构,所以当你 rescue Exception
中的所有中救出,包括子类,如 SyntaxError
, LoadError
和中断
。
Exception
is the root of Ruby's exception hierarchy, so when you rescue Exception
you rescue from everything, including subclasses such as SyntaxError
, LoadError
, and Interrupt
.
拯救中断
阻止用户使用 CTRL C 退出程序。
Rescuing Interrupt
prevents the user from using CTRLC to exit the program.
拯救 SignalException
程序正确响应信号。除了 kill -9
,否则将不可用。
Rescuing SignalException
prevents the program from responding correctly to signals. It will be unkillable except by kill -9
.
拯救 SyntaxError
意味着失败的 eval
将静默地执行。
Rescuing SyntaxError
means that eval
s that fail will do so silently.
所有这些都可以通过运行这个程序,并尝试 CTRL C 或 kill
它:
All of these can be shown by running this program, and trying to CTRLC or kill
it:
loop do
begin
sleep 1
eval "djsakru3924r9eiuorwju3498 += 5u84fior8u8t4ruyf8ihiure"
rescue Exception
puts "I refuse to fail or be stopped!"
end
end
从 code>甚至不是默认值。执行
Rescuing from Exception
isn't even the default. Doing
begin
# iceberg!
rescue
# lifeboats
end
code>异常,它从 StandardError
中拯救。您应该通常指定比默认的 StandardError
更具体的内容,但从 Exception
broadens 范围而不是缩小范围,并且可能会造成灾难性的后果,并且使得狩猎非常困难。
does not rescue from Exception
, it rescues from StandardError
. You should generally specify something more specific than the default StandardError
, but rescuing from Exception
broadens the scope rather than narrowing it, and can have catastrophic results and make bug-hunting extremely difficult.
如果你有您想要从 StandardError
中拯救的情况,您需要一个变量,例外情况下,您可以使用以下形式:
If you have a situation where you do want to rescue from StandardError
and you need a variable with the exception, you can use this form:
begin
# iceberg!
rescue => e
# lifeboats
end
相当于:
begin
# iceberg!
rescue StandardError => e
# lifeboats
end
从异常to to rescue ane ane ane the the the p p p One One p p p p p p p p p p p p p:::::::::::::::::::: >
One of the few common cases where it’s sane to rescue from Exception
is for logging/reporting purposes, in which case you should immediately re-raise the exception:
begin
# iceberg?
rescue Exception => e
# do some logging
raise e # not enough lifeboats ;)
end
这篇关于为什么“救援Exception =>在Ruby中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!