Ruby线程:如何在不调用.join的情况下捕获异常?

时间:2014-11-11 21:14:45

标签: ruby multithreading

如何在不使用.join的情况下观察和挽救线程中发生的错误?我现在的代码:

Thread.abort_on_exception = true
begin
    a = Thread.new { errory_code }
rescue Exception => detail
    puts detail.message
end

sleep 1 #so that thread has enough time to execute 

如果我理解正确,Thread.abort_on_exception = true会中止线程执行(即引发异常)。但为什么救援没有抓住它呢?

2 个答案:

答案 0 :(得分:3)

你期望rescue操作能够从Ruby退出begin ... end块之后很久就运行的一些代码中捕获异常。那不会发生。

请记住,当您处理线程时,事情会发生故障。

您可以捕获的唯一例外是与线程创建有关的例外。线程内部发生的事情是另一个世界。

使用join强制您的代码等待线程完成,以便正确排序。然后可以捕获线程异常。

答案 1 :(得分:1)

我想出了如何做到这一点 - 我只需要将我的线程内部包装到这样的救援块中:

Thread.abort_on_exception = true

a = Thread.new do 
    begin                      #new
        errory_code 
    rescue Exception => detail #new
        puts detail.message    #new
    end                        #new
end

sleep 1 #so that thread has enough time to execute 

这是一个非常明显的解决方案,但是,因为我花了这么长时间才想到它,所以希望能帮助别人。