我正在查看有关 ruby api 调用的 mandrill 文档 https://mandrillapp.com/api/docs/users.ruby.html#method=ping我注意到他们拯救了 Mandrill::Error
然后 raise
另一个异常。
我很好奇为什么有人会捕获一个异常然后引发另一个异常。这对我来说没有意义。
begin
mandrill = Mandrill::API.new 'YOUR_API_KEY'
result = mandrill.users.ping
# {"PING"=>"PONG!"}
rescue Mandrill::Error => e
# Mandrill errors are thrown as exceptions
puts "A mandrill error occurred: #{e.class} - #{e.message}"
# A mandrill error occurred: Mandrill::InvalidKeyError - Invalid API key
raise
end
最佳答案
rescue Mandrill::Error => e
# Mandrill errors are thrown as exceptions
puts "A mandrill error occurred: #{e.class} - #{e.message}"
# A mandrill error occurred: Mandrill::InvalidKeyError - Invalid API key
raise
end
在这种情况下,相同的异常被“重新引发”。此 rescue
block 的唯一原因是记录有关异常的特定信息。
begin/rescue
block 通常在对异常特别感兴趣时以这种方式使用,因此作者希望打印/记录异常信息。当下一个 rescue
block 不打印任何异常信息而是静默处理它时尤其如此。
关于ruby-on-rails - 为什么要拯救异常然后引发异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24175633/