title: Handling exceptions raised in a Ruby thread
body: <p>I am looking for a solution of classic problem of exception handling. Consider following piece of code:</p>
  
  <pre><code>def foo(n)
    puts " for #{n}"
    sleep n
    raise "after #{n}"
  end
  
  begin
    threads = []
    [5, 15, 20, 3].each do |i|
      threads &lt;&lt; Thread.new do
        foo(i)
      end
    end
  
    threads.each(&amp;:join)      
  rescue Exception =&gt; e
    puts "EXCEPTION: #{e.inspect}"
    puts "MESSAGE: #{e.message}"
  end
  </code></pre>
  
  <p>This code catches the exception after 5 seconds.</p>
  
  <p>But if I change the array as <code>[15, 5, 20, 3]</code>, above code catch the exception after 15 seconds. In short, it always catch the exception raised in first thread.</p>
  
  <p>Any idea, why so. Why doesn't it catch the exception after 3 seconds each time? How do I catch the first raised exception by any thread?</p>