Skip to content
Related Articles

Related Articles

Ruby | Exception Handling in Threads | Set – 1
  • Last Updated : 19 Dec, 2018
GeeksforGeeks - Summer Carnival Banner

Threads can also contain exceptions. In Ruby threads, the only exception arose in the main thread is handled but if an exception arises in the thread(other than main thread) cause the termination of the thread. The arising of an exception in a thread other than the main thread depends upon abort_on_exception method. The default value of abort_on_exception is false. When the value of abort_on_exception is false it means the unhandled exception aborts the current thread and the rest of the threads will continue running.
You can also change the setting of abort_on_exception by using abort_on_exception=true or $DEBUG to true. Ruby threads also provided a method to handle the exceptions, i.e. ::handle_interrupt. This will method handle exceptions asynchronously.

Example:




# Ruby program to illustrate 
# the exception in thread
  
#!/usr/bin/ruby  
  
threads = []
4.times do |value|
  
    threads << Thread.new(value) do |a|
  
        # raising an error when a become 2
        raise "oops error!" if a == 2
  
print "#{a}\n"
end
  
end
threads.each {|b| b.join }

Output:

0
3
1
main.rb:12:in `block (2 levels) in 
': oops error! (RuntimeError)

Note: Thread.Join method is used to wait for the finishing of a particular thread. Because when a Ruby program terminates, all the thread are killed, irrespective of their states. We can also save the exception as shown in the below example:

Example:






# Ruby program to illustrate hwo to 
# escape the exception
  
#!/usr/bin/ruby  
  
threads = []
  
5.times do |value|
    threads << Thread.new(value) do |a|
        raise "oops error!" if a == 3
print "#{a}\n"
end
  
end
  
threads.each do |x|
begin
  
x.join
  
# using rescue method
rescue RuntimeError => y
    puts "Failed:: #{y.message}"
end
end

Output:

0
1
4
2
Failed:: oops error!

Now set the value of abort_on_exception= true, it kills the thread which contains an exception. Once the thread is dead, no more output will produce.

Example:




# Ruby program to illustrate the killing
# of thread in which exception raised 
  
#!/usr/bin/ruby  
  
# setting the value of abort_on_exception
Thread.abort_on_exception = true
  
threads = []
  
5.times do |value|
    threads << Thread.new(value) do |a|
    raise "oops error!" if a == 3
  
print "#{a}\n"
end
  
end
  
# using Thread.Join Method
threads.each {|b| b.join }

Output:

0
1
2
main.rb:13:in `block (2 levels) in 
': oops error! (RuntimeError)

The execution of thread(other than main thread) as shown below:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :