sawa
sawa

Reputation: 168101

How to capture an exception from another thread

How can I capture an exception from another thread?

I found an answer in How to get error messages from ruby threads that suggests using catch, and I think that is the way I want to go, but I cannot not fully figure out how to do it. Or is there a better way? I also found an answer suggesting to use Queue class, but have concern that it may be overkill.

Upvotes: 2

Views: 204

Answers (1)

tadman
tadman

Reputation: 211580

If you turn on abort_on_exception then you won't have a chance to catch it. You can, however, leave that off and simply catch it when you do the join operation on your thread.

thread = Thread.new do
  raise "Uh oh"
end

begin
  thread.join
rescue => e
  puts "Caught exception: #{e}"
end

The alternative is to make the thread catch its own exception and save it somewhere you can fetch it from later. For instance:

exceptions = { }

Thread.new do
  begin
    raise "Uh oh"
  rescue => e
    exceptions[Thread.current] = e
  end
end

sleep(1)

puts exceptions.inspect
# => {#<Thread:0x007f9832889920 dead>=>#<RuntimeError: Uh oh>}

Upvotes: 2

Related Questions