【问题标题】:What is the Rubyist way to catch an exception raised in a rescue block?捕捉救援块中引发的异常的 Rubyist 方法是什么?
【发布时间】:2016-03-21 23:19:58
【问题描述】:

假设我有以下内容:

begin
  raise 'Exception!'
rescue => e
  puts "Rescued exception: #{e.message}"
  raise 'Something I did in this block raised an exception!'
end

Rubyist 捕获第二个异常的方法是什么?最好将整个东西包装在另一个开始救援块中,还是有更优雅的解决方案?

【问题讨论】:

  • 如果你在 Rails 中,还有rescue_from

标签: ruby exception-handling


【解决方案1】:

我不能以 Rubyist 的方式说话,但这是 a Rubyist 的方式:

使救援代码尽可能防错。如果无法确保异常非常少的错误证明,那么与其在救援块内开始嵌套救援块,不如调用另一个处理自己的异常的方法,例如:

def foo
  1/0
rescue
  complicated_foo_error_handler
end

private

def complicated_foo_error_handler
  # handle foo errors
rescue
  complicated_complicated_foo_error_handler_error_handler
end

def complicated_complicated_foo_error_handler_error_handler
  # handle complicated_foo_error_handler errors
rescue
  STDERR.puts 'I give up!'
  exit false
end

【讨论】:

  • 假设您要在处理程序中处理异常。有时您想从救援中传播异常,或者引发一个不同的异常,以便更准确地为调用者描述问题。我不是 100% 确定 OP 需要什么。
猜你喜欢
  • 2021-12-19
  • 2012-05-08
  • 1970-01-01
  • 2017-05-19
  • 2013-07-13
  • 1970-01-01
  • 2021-10-24
  • 2017-03-09
  • 1970-01-01
相关资源
最近更新 更多