Open In App

Ruby | Exception Handling in Threads | Set – 1

Improve
Improve
Like Article
Like
Save
Share
Report

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




# 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




# Ruby program to illustrate how 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




# 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:



Last Updated : 12 Sep, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads