Exception handling lets the user define the course of action in case an error is raised. When an error arises in the normal execution of the code, the alternative block of code is executed instead.
Ruby also provides a separate class for exceptions, the Exception class, which contains different types of methods.
Particular keywords help with exception handling. The begin
and end
keywords enclose both the main block of code and the rescue block.
The main block of code is indented after the raise
keyword, while the code to be executed in case of an error is indented after rescue
.
begin
raise
# block where an exception is raised
rescue
# block where exception is rescued
end
If the exception is not handled by one rescue block, it will be handled by the next run of the rescue code, using the retry
command. However, extra care is required with the retry
statement as it may lead to an infinite loop.
We can use the else
block to set up an alternate path for execution. If no exception is raised, the else block will run.
We can use the ensure
path to hold code that must run, irrespective of whether an exception was raised or not.
The following block of code shows how exception handling is done in Ruby:
# Example code for exception handling# Exception handling block beginsbeginputs 'Start program...'# using raise to create an exceptionraise 'Raising exception here!'puts 'After exception.'# using Rescue methodrescueputs 'Rescued exception!'else # this block runs if no exception raisesputs "All okay."ensure # this block always runsputs "Ensure block."# Exception handling block endsendputs 'Outside the exception handling block.'
Free Resources