Updated April 6, 2023
Introduction to try catch in Ruby
Many times when we are working with certain difficult set of scenario where it is very much possible that code will fail its execution, for example in case if we are going to write some content on any file and that file does not exist in this kind of cases code execution is going to stop which is not correct, we need to handle it. In Ruby we have a way to deal with these cases, we have begin, end(default try catch) and we can use try and catch, both try catch and raise rescue used for the same purpose, one will throw exception(throw or raise) with any specific name inside another(catch or rescue).
Syntax of try catch in Ruby
Syntax with catch and throw, we can have three different types of syntax to handle exceptions which are with try catch , with begin and rescue and else.
1. Syntax with catch and try
Here in the below example we are throwing an exception with name nameexception and the same exception will be caught here with the same name (nameexception). So in case any exception happens it will be tracked in the catch block.
throw :nameexception
#This is your comment and code block , it would not execute .
catch :nameexception do
#After the throw happens, a matching catch with an exception name will be handled here .
end
2. Syntax with begin and rescue
Here in this case an exception will be raised inside the rescue block and inside the ensure block can send the exception details.
begin
# - Send exception in rescue block
rescue sendAnyException
# -
rescue AnotherTypeOfException
# - Ensure block for conforming about the exception
ensure
end
3. Syntax with else
In this type of case we are handling or catching exceptions along with using the else block to display the proper message .
begin
rescue
#send the name of exception here
else
# If not an exception we can do something here .
ensure
#Confirming the exception inside the esure block
end
How try-catch works in Ruby?
We can use the try and catch in case opening any file and in case handling database related queries. Because in these cases we can not predict nature. File can be there and can not be there, in the same way it is possible that the query which we are writing tables may not be there inside the database.
1. First try catch (pure try and catch)
- Try and catch both are working together, once any exceptions happens inside the try block it will throw an exception, this exception can be either custom or we can define some name for the exception, with the same name inside the catch block the exception will be caught.
- We can also throw some object of exemptions from the try block and that particular object will be handled inside the catch block.
2. Ruby Internal try catch (raise and rescue)
- If we see about the try catch of begin and rescue, here every code which we write inside the begin block is protected, which means all the codes from the begin to the rescue are in safe mode (any exception will be handled there).
- In case exceptions happen in the begin block it will halt and control will go between rescue and end, and we can return a valid message for the user in case of exceptions.
- Every time for a rescue statement Ruby checks and compares the exception raised for each parameter.
Examples of try catch in Ruby
Given below are the examples mentioned:
Example #1
In this example we are throwing an exception with the name nameOfException and with the same name we are catching the exception.
- First we have defined a function with the name callAndFetch and this function will get a parameter student.
- And in the next block we are sending the error or exception from the begin block.
- The exception which we throw with the same name will be caught and it will print the details of the exception.
Code:
def callAndFetch(prompt)
print prompt
responseValue = readline.chomp
throw :nameOfException if responseValue == "!"
return res
end
catch :nameOfException do
student = callAndFetch("Student: ")
end
callAndFetch("Student:")
Output:
Example #2
In this example we are throwing an exception with the name nameOfException and with the same name we are catching the exception.
- First we have defined a function with the name callAndFetch and this function will get a parameter student.
- And in the next block we are sending the error or exception from the begin block.
- The exception which we throw with the same name will be caught and it will print the details of the exception.
- Here after calling the function callAndFetch with the parameter Student, we again call it with the parameter Teacher.
- But a call with parameter Teacher will not catch the exception as an exception has occurred so no further execution.
Code:
def callAndFetch(prompt)
print prompt
responseValue = readline.chomp
throw :nameOfException if responseValue == "!"
return responseValue
end
catch :nameOfException do
student = callAndFetch("Student:")
teacher = callAndFetch("Teacher:")
end
callAndFetch("Student:")
callAndFetch("Teacher:")
Output:
Example #3
In this type of try catch used the Ruby begin and rescue feature to handle. It works almost similar to the simple try catch, only thing it has few more features like else, ensure to deal exceptions. We see the example as we have rescued an exception which was raised inside the begin block an we have the rescue statement will fetch the data exception.message, and we will get the message raised by raise statement inside the rescue.
Code:
begin
puts 'Searching for the file xyz.txt,success as the file is available'
raise 'Searching for the file abc.txt,fail as file is not there'
rescue Exception => exception
puts exception.message
puts exception.backtrace.inspect
ensure
puts "It was an exception , it need to be take care"
end
Output:
Conclusion
From this tutorial we learned about the flow of try and catch of Ruby, we learned the places where we can use the try catch and also we learned some try catches which are indirectly available in the Ruby like rescue and raise also we learned about how they work.
Recommended Articles
We hope that this EDUCBA information on “try catch in Ruby” was beneficial to you. You can view EDUCBA’s recommended articles for more information.