Ruby 线程 : how to catch an exception without calling . 加入?

标签 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 中止线程执行(即引发异常)。但为什么救援没有捕获它呢?

最佳答案

您期望 rescue 操作从 Ruby 退出 begin ... end block 后运行很长时间的代码中捕获异常。这不会发生。

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

您可以捕获的唯一异常是与线程创建相关的异常。线程内部发生的事情完全是另一个世界。

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

关于Ruby 线程 : how to catch an exception without calling . 加入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26874711/

相关文章:

ruby-on-rails - fixtures 会触发模型回调吗?

ruby-on-rails - Ruby on Rails——静态页面的独立 Controller 方法

multithreading - 在采用 `&mut self`(如 drop)的方法中加入线程会导致 "cannot move out of borrowed content"

ruby-on-rails - 阻止创建一个类的多个对象

ruby-on-rails - 在 Ruby 中为 S3 Bucket 生成预签名 URL 的推荐方法

c++ - 我想弄清楚如何在简单的 Qt gui 应用程序中使用线程

c# - ASP.NET MVC 的异步 Controller 与多线程

c++ - Linux - 获取线程堆栈内存的开始和结束

Python 线程通信不起作用

ruby-on-rails - 是否有 Rails 控制台命令(Rails 3+)来重新加载更改后的代码?