Iteration Podcast
Exceptional Failure
Exceptional Failure
In this short season, we are going through EXceptional Ruby by Advi Grimm
What is a failure?
Let's talk about some definitions first:
- Exception - the occurrence of an abnormal condition during the execution of a software element.
- Failure - the inability of a software element to satisfy its purpose
- Error - the presence in the software of some element not satisfying its specification
"Failures cause exceptions which are due to errors"
- Failures - methods are thought to be designed to fulfill a contract. when they don't fulfill the contract, they fail
The life-cycle of an exception
- Exceptions are raised with either the
raise
orfail
methods - In Ruby, we signal failures with exceptions
🗣 Discussion: When do you find yourself using raise
?
🗣 Discussion: When do you find yourself using rescue
?
- The
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 failure
syntax
-
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 therescue
is matchedrescue 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
- Order matters when stacking multiple rescue clauses. the RuntimeError rescue block will never execute!
🗣 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
- Ruby gives you the power to retry
- I can see how this might be useful for making API calls
- Be super careful that your 'giving up' criteria will eventually be met
- Retry is nice for things that are unreliable
Picks:
JP: Overcast https://overcast.fm/
John: Apple Refurbished