Closed Hannah0701 closed 3 weeks ago
In Ruby, error handling is done using begin, rescue, else, ensure, and end keywords. These are similar to the try-catch blocks in other languages.
Here's an example of a simple error handling:
begin
# Code that might raise an exception
1 / 0
rescue ZeroDivisionError => e
puts "Error: #{e.message}"
end
In this example, if an error of type ZeroDivisionError occurs in the begin block, the rescue block will be executed.
You can also handle multiple types of errors:
begin
# Code that might raise an exception
1 / 0
rescue ZeroDivisionError => e
puts "Error: #{e.message}"
rescue TypeError => e
puts "Error: #{e.message}"
end
The ensure block is always executed, whether an exception is raised or not:
begin
# Code that might raise an exception
1 / 0
rescue ZeroDivisionError => e
puts "Error: #{e.message}"
ensure
puts "This code runs no matter what"
end
You can also define your own custom exceptions by creating a new class that inherits from StandardError:
class MyCustomError < StandardError; end
begin
# Code that might raise an exception
raise MyCustomError, "This is a custom error"
rescue MyCustomError => e
puts "Error: #{e.message}"
end
In this example, MyCustomError is a custom exception class. The raise keyword is used to raise an exception.
Construct programs that gracefully handles errors.
Understand how to handle errors using try-catch blocks. Learn about raising and handling custom exceptions.