在Ruby中捕获异常后重新引发(相同异常) [英] Reraise (same exception) after catching an exception in Ruby
问题描述
我试图通过捕获异常来提高我的Ruby技能。我想知道当您有多个方法调用时,引发相同类型的异常是否很常见。那么,以下代码有意义吗?是否可以引发相同类型的异常,还是不应该在处理方法上捕获它?
I am trying to improve my Ruby skills by catching exceptions. I want to know if it is common to reraise the same kind of exception when you have several method calls. So, would the following code make sense? Is it ok to reraise the same kind of exception, or should I not catch it on the process method?
class Logo
def process
begin
@processed_logo = LogoProcessor::create_image(self.src)
rescue CustomException
raise CustomException
end
end
end
module LogoProcessor
def self.create_image
raise CustomException if some_condition
end
end
推荐答案
有时我们只是想知道发生了什么错误 ,而不必真正地处理错误。
Sometimes we just want to know an error happened, without having to actually handle the error.
通常,负责处理错误的是对象的用户:调用者。如果我们对错误感兴趣但又不想承担该责任怎么办?我们可以挽救错误,执行所需的任何操作,然后将信号传播到堆栈中,就像什么都没发生一样。
It is often the case that the one responsible for handling errors is user of the object: the caller. What if we are interested in the error, but don't want to assume that responsibility? We rescue the error, do whatever we need to do and then propagate the signal up the stack as if nothing had happened.
例如,如果我们想记录错误消息,然后让呼叫者处理?
For example, what if we wanted to log the error message and then let the caller deal with it?
begin
this_will_fail!
rescue Failure => error
log.error error.message
raise
end
调用 raise
不带任何参数将引发最后一个错误。在我们的案例中,我们正在引发错误
。
在您提出的示例中,重新根本没有必要提出这个错误。您可以简单地让它自然地在堆栈中传播。您的示例中的唯一区别是,您要创建一个新的错误对象并将其引发,而不是重新引发上一个错误对象。
In the example you presented in your question, re-raising the error is simply not necessary. You could simply let it propagate up the stack naturally. The only difference in your example is you're creating a new error object and raising it instead of re-raising the last one.
这篇关于在Ruby中捕获异常后重新引发(相同异常)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!