I need to immediately catch exceptions in threads and stop all threads, so I'm using abort_on_exception in my script. Unfortunately this means the exception is not raised to the parent thread - perhaps this is because the exception ends up happening in a global scope??
Anyways, here's an example showing the issue:
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
How can I rescue that exception that's raised in the thread when using abort_on_exception?
Here's a new example that shows something even more boggling. The thread is able to kill execution inside the begin block, but it does it without raising any exceptions??
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
Ah - I figured it out.
The abort_on_exception send, obviously, an abort. The thread is irrelevant, our rescue won't see a basic abort either:
begin
abort
puts "This doesn't execute"
rescue => e
puts "This also doesn't execute"
ensure
puts "But this does?? #{$!}"
end
The solution is to use a 'rescue Exception' which also catches the abort.
begin
abort
puts "This doesn't execute"
rescue Exception => e
puts "Now we're executed!"
end