What happens if a thread raises an unhandled exception? It depends on
the setting of the
https://abort_on_exception
flag, documented on pages 384 and
387.
If
abort_on_exception
is
false
, the default
condition, an unhandled exception simply kills the current
thread---all the rest continue to run. In the following example,
thread number 3 blows up and fails to produce any output. However,
you can still see the trace from the other threads.
threads = []
6.times { |i|
threads << Thread.new(i) {
raise "Boom!" if i == 3
puts i
}
}
threads.each {|t| t.join }
|
produces:
01
2
45prog.rb:4: Boom! (RuntimeError)
from prog.rb:8:in `join'
from prog.rb:8
from prog.rb:8:in `each'
from prog.rb:8
|
However, set
abort_on_exception
to
true
, and an
unhandled exception kills all running threads. Once thread 3 dies,
no more output is produced.
Thread.abort_on_exception = true
threads = []
6.times { |i|
threads << Thread.new(i) {
raise "Boom!" if i == 3
puts i
}
}
threads.each {|t| t.join }
|
produces:
01
2
prog.rb:5: Boom! (RuntimeError)
from prog.rb:7:in `initialize'
from prog.rb:7:in `new'
from prog.rb:7
from prog.rb:3:in `times'
from prog.rb:3
|