Exceptions and Safety
Ensure Clause
ensure runs cleanup-style code after a protected operation succeeds or fails.
Ensure Clause
ensure_clause.rb
mode =
status = "starting"
begin
status = "working"
raise "temporary failure" if mode == "fail"
status = "finished"
puts "status=#{status}"
rescue RuntimeError
status = "rescued"
puts "status=#{status}"
ensure
puts "ensure=ran"
end
puts "mode=#{mode}"
mode =
status = "starting"
begin
status = "working"
raise "temporary failure" if mode == "fail"
status = "finished"
puts "status=#{status}"
rescue RuntimeError
status = "rescued"
puts "status=#{status}"
ensure
puts "ensure=ran"
end
puts "mode=#{mode}"
mode =
status = "starting"
begin
status = "working"
raise "temporary failure" if mode == "fail"
status = "finished"
puts "status=#{status}"
rescue RuntimeError
status = "rescued"
puts "status=#{status}"
ensure
puts "ensure=ran"
end
puts "mode=#{mode}"
ensure
An `ensure` clause runs after the `begin` body and any matching `rescue`.