This tutorial explains How to handle errors in the Ruby language.
In any program, if an error or exception is thrown, the Code stops its execution and exits the program.
To avoid a graceful exit from a program, Exception handling is introduced.
Ruby Exception Handling
Ruby language provides the following syntax block for handling exceptions.
- begin
- rescue
- else
- ensure
- end
Syntax
begin
# code that might throw an error or exception
rescue
# handle errors
# Multiple rescue statements for multiple exceptions
else
# Executes if there are no errors
ensure
# Code Clean up
end
begin
: contains code statements that might throw an exceptionrescue
: Contains code for handling exceptions. It can contain multiple rescue statements.else
: executes code when there are no exceptionsensure
: code cleanup and executes irrespective error thrown or notend
is the end of handling exceptions.
Here is an example
begin
# code throws an error
rescue StandardError
rescue TypeError => e
# Handle multiple exceptions
puts "Error: #{e}"
rescue StandardError => e
# Handle other exceptions
puts "Standard Error: #{e.message}"
end
- How to handle multiple exception types.
Single rescue can be declared with multiple exceptions separated by a comma.
rescue StandardError, TypeError => e
How to create a Custom Exception and rescue it
Create a Custom Exception Class by extending StandardError
.
Write an initialize method with a default message.
class DuplicateRecordError < StandardError
def initialize(message = "Duplicate Record error.")
super
end
end
Once a Custom Exception is created, you can handle exceptions using rescue.
rescue DuplicateRecordError => e
end
Here is an example of Own Custom Exception
class DuplicateRecordError < StandardError
def initialize(message = "Duplicate Record error.")
super
end
end
begin
raise DuplicateRecordError
rescue DuplicateRecordError => e
puts "Own Error: #{e.message}" #Custom Error: Duplicate Record error.
end