gpt4 book ai didi

ruby 无法从 Thread.abort_on_exception 中拯救或看到中止

转载 作者:数据小太阳 更新时间:2023-10-29 07:56:44 25 4
gpt4 key购买 nike

我需要立即捕获线程中的异常并停止所有线程,因此我在我的脚本中使用了 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 时线程中引发的异常?

这是一个新的例子,它展示了更令人难以置信的东西。该线程能够终止开始 block 内的执行,但它不会引发任何异常??

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

最佳答案

啊 - 我想通了。

显然,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

关于ruby 无法从 Thread.abort_on_exception 中拯救或看到中止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13203268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com