begin ...rescue TooHotError => too_hot # This code is run if a TooHotError occurs rescue TooColdError => too_cold # This code is run if a TooColdError occurs else # This code is run if no exception occurred at allensure # This code is always run, regardless of whether an exception occurredend
Multiple rescues
Second rescue’s exception class also covers first rescue’s exception class
The first rescue block will run
class TimeoutError < StandardError; end;begin raise TimeoutErrorrescue TimeoutError puts "Inside the first rescue"rescue StandardError puts "Inside the second rescue"end#=> Inside the first rescue
The retry keyword
Ruby provides the retry keyword to retry the code inside the begin..end block