我需要立即捕获线程中的异常并停止所有线程,所以我在我的脚本中使用abort_on_exception。不幸的是,这意味着异常不会引发到父线程 - 也许这是因为异常最终发生在全局范围内?
无论如何,这是一个显示问题的例子:
Thread.abort_on_exception = true
begin
t = Thread.new {
puts "Start thread"
raise saveMe
puts "Never here.."
}
t.join
rescue => e
puts "RESCUE: #{e}"
ensure
puts "ENSURE"
end
如何在使用abort_on_exception时解除线程中引发的异常?
这是一个新的例子,显示更令人难以置信的东西。该线程能够终止开始块内的执行,但它会在不引发任何异常的情况下执行它吗?
Thread.abort_on_exception = true
begin
t = Thread.new { raise saveMe }
sleep 1
puts "This doesn't execute"
rescue => e
puts "This also doesn't execute"
ensure
puts "But this does??"
end
答案 0 :(得分:4)
abort_on_exception显然是中止发送。线程无关紧要,我们的救援也不会看到基本的中止:
begin
abort
puts "This doesn't execute"
rescue => e
puts "This also doesn't execute"
ensure
puts "But this does?? #{$!}"
end
解决方案是使用'救援异常'来捕获中止。
begin
abort
puts "This doesn't execute"
rescue Exception => e
puts "Now we're executed!"
end