我现在遇到一个问题,我无法看到我的子线程在哪里吐出错误消息,这使得调试变得困难.
例如:
Thread.new{ a = 1/0 }
是否有任何方法可以在stderr打印出所有线程错误?
将Thread类' abort_on_exception
标志设置为true.
或者,将线程主体包装在throw/catch块中,并将异常转储到catch中.
设置$DEBUG
为true(您可以从命令行执行此操作-d
),您将获得
ruby -d bad_thread.rb
Exception `LoadError' at /usr/lib/ruby/site_ruby/1.8/rubygems.rb:1113 - no such file to load -- rubygems/defaults/operating_system
Exception `LoadError' at /usr/lib/ruby/site_ruby/1.8/rubygems/config_file.rb:34 - no such file to load -- Win32API
Exception `ZeroDivisionError' at bad_thread.rb:2 - divided by 0
bad_thread.rb:2:in `/': divided by 0 (ZeroDivisionError)
from bad_thread.rb:2
from bad_thread.rb:1:in `initialize'
from bad_thread.rb:1:in `new'
from bad_thread.rb:1
这应该捕获您没有明确处理的任何错误并将它们打印到STDOUT.
require 'pp' Thread.new { begin a = 1/0 rescue pp $! end }
结果: #