Control Flow
Exception Handling in Ruby
Used to mitigate errors in code and prevent program crashing during runtime. It 'tries' a block of code that could give an error. If the error (exception) is caught, it will execute a different block of code rather than crash the program.
Syntax
begin
# code that may give an error
#error to catch, if no type is provided it catches all errors, condition is optional
#error message is saved to the exception object
#and can be accessed using errorObject.message
raise ExceptionType, "Error message" condition
rescue ExceptionType => errorObject
#code to execute if specific type of error occurs, if no error provided it catches all
retry #used to try the code
else
#code to execute if exception doesn't occur
ensure
#this code always executes no matter what
end
Notes
The ExceptionType is the type of error which can occur. Most are defined within Ruby.
User-defined exceptions are created by using the raise statement and providing an error message.
The retry statement makes the program go back to the beginning of the block on error detection.
Example
begin
test_score = gets.chomp
test_out_of = gets.chomp
#user defined exception
if test_out_of < 0
raise "Test can't be out of a negative number!"
end
#this code may generate an error if test is out of 0
test_percent = test_score / test_out_of
#if test_out_of is zero, if will raise a ZeroDivisorException
rescue ZeroDivisionError
puts "You can't make your test out of zero!"
rescue Exception => e #user defined exception
puts e.message
end