This week we talk about what is a failure, and the life-cycle of an exception.
In this short season, we are going through EXceptional Ruby by Advi Grimm
Let's talk about some definitions first:
"Failures cause exceptions which are due to errors"
raise
or fail
methods🗣 Discussion: When do you find yourself using raise
?
🗣 Discussion: When do you find yourself using rescue
?
rescue
clause should be a short sequence of simple instructions designed to bring the object back to a stable state and to either retry the operation or terminate with a failuresyntax
Starts with the rescue
keyword, followed by one or more classes or modules to match, then a hash rocket and the variable name to which the matching exception will be assigned
Subsequent lines of code up to an end
keyword will be executed if the rescue
is matched
rescue IOError => e
puts "Error while writing to file: #{e.message}"
end
Moar Code
begin
raise RuntimeError, 'specific error'
rescue StandardError => error
puts "Generic error handler: #{error.inspect}"
rescue RuntimeError => error
puts "runtime error handler: #{error.inspect}"
end
🗣 Discussion: Have you ever used retry
?
tries = 0
begin
tries += 1
puts "trying #{tries}"
raise
rescue
retry if tries < 3
puts 'I give up'
end
Picks:
JP: Overcast https://overcast.fm/
John: Apple Refurbished