Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com
Answertopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Ruby Programming
Previous Page Home Next Page

Threads and Exceptions

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
Ruby Programming
Previous Page Home Next Page

 
 
  Published under the terms of the Open Publication License Design by Interspire