Introduction
Exception handling is a technique in Ruby that defines how to handle an error raised in a programme. An unwelcome or unexpected occurrence that occurs during the execution of a programme, i.e., at run time and disturbs the usual flow of the program's instructions, is referred to as an error. As a result, the rescue block will handle these types of problems. An Exception class, which contains several types of methods, is also provided by Ruby as a separate class for an exception.
Syntax
begin
raise
# block that raise’s exception
rescue
# block that rescue’s exception
end
The begin-rescue
Ruby's exception handling starts with the begin-rescue block, similar to PHP's try-catch. In short, the begin-rescue code block can be used to handle raised exceptions without disrupting the program's execution. To put it another way, you can start executing a block of code and catch any exceptions that occur.
Let us see a simple program that will help you to understand the exception handling using the begin-rescue keyword.
Need of begin-rescue block
Code
puts 1/0
puts 4/2
Output
main.rb:1:in `/': divided by 0 (ZeroDivisionError)
from main.rb:1:in `<main>'
Explanation
In the above code, we get an error it says that in the first line, we are dividing the number by zero. Due to that one specific line, we are unable to run the second line too. This problem can be solved using a begin-rescue code block in the following way. (Use the begin-rescue code block whenever you are suspicious about the particular line.)
begin-rescue block
Code
begin
puts 1/0
rescue
puts "Hey first line has some error !!"
end
puts 4/2
Output
Hey first line has some error !!
2
Explanation
As we know that the first line has some errors, so we are adding that particular line to the begin-rescue block. The begin-rescue block tries to execute the particular line, and if any error occurs in the particular line, it simply skips the specific line and executes the rescue block.
As "1/0" is not a valid operation, so it executes the rescue block. Also, we can see that "puts 4/2" gets executed without any disturbance of the error that occurred due to the "1/0" operation.
Getting the Error
In the above example, the error that occurred was easy to detect manually, but in some cases, the errors are very hard to detect manually. So there is an easy way to print an incurred error.
Code
begin
puts 1/0
rescue => e
puts e
end
puts 4/2
Output
divided by 0
2
Explanation
As we can see the output of the programme. We are getting the display of the error that we incurred while executing the programme.