Evgenia Karunus
Evgenia Karunus

Reputation: 11202

Ruby threads: how to catch an exception without calling .join?

How to observe and rescue an error that happens in the thread without using .join? The code that I have right now:

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 

If I understand it correctly, Thread.abort_on_exception = true aborts thread execution (that is, raises an exception). But why rescue doesn't catch it?

Upvotes: 3

Views: 938

Answers (2)

Evgenia Karunus
Evgenia Karunus

Reputation: 11202

I figured out how to do it - I just need to wrap insides of my thread into a rescue block like that:

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 

Which is a horribly obvious solution, - but, since it took me so long to think of it, will hopefully help somebody.

Upvotes: 2

tadman
tadman

Reputation: 211580

You're expecting the rescue operation to catch exceptions from a bit of code that's run long after Ruby's exited that begin ... end block. That's not going to happen.

Remember when you're dealing with threads, things happen out of order.

The only exceptions you can catch there are those relating to the creation of the thread. What happens inside the thread is a whole other world.

Using join forces your code to wait until the thread is complete, so that gets the ordering correct. Thread exceptions can then be caught.

Upvotes: 3

Related Questions