Ruby Exceptions
begin, rescue, else, ensure and retry handle errors. raise throws an exception, and you can define your own error classes by inheriting from StandardError.
Example
class TooYoung < StandardError; end
def check(a) = a < 18 ? raise(TooYoung, "age #{a}") : "ok"
begin
puts check(20)
puts check(10)
rescue TooYoung => e
puts "caught #{e.message}"
else
puts "no error"
ensure
puts "cleanup"
endResult
ok caught age 10 cleanup
Exercise
Throw an error.
ArgumentErrorQuiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.