ensure and cleanup
suggest changeAn ensure clause holds code that runs however its block is left: normally, through an exception, or with return, break, next or throw. Use it to release whatever the block acquired, such as files, sockets, database connections, locks, temporary files or a changed working directory.
This article covers how ensure behaves, the pitfalls to avoid, and the block-based pattern Ruby code uses for cleanup instead of writing ensure by hand. For the basics of rescue see Handling an exception, and for a short introduction see Code That Should Always Run.
When ensure runs
You can attach ensure to a begin block, to a method body (no begin needed), or to a do ... end block:
def demo(mode)
puts "start #{mode}"
case mode
when :ok then puts "work done"
when :raise then raise ArgumentError, "bad input"
when :return then return :early
end
:finished
rescue ArgumentError => e
puts "rescued: #{e.message}"
:rescued
ensure
puts "cleanup #{mode}"
end
p demo(:ok)
p demo(:raise)
p demo(:return)
start ok
work done
cleanup ok
:finished
start raise
rescued: bad input
cleanup raise
:rescued
start return
cleanup return
:early
You don't need a rescue clause to use ensure. Without one, the cleanup runs and then the exception continues up to the caller:
def risky
puts "opening"
raise IOError, "disk full"
ensure
puts "closing"
end
begin
risky
rescue IOError => e
puts "caller got: #{e.message}"
end
opening
closing
caller got: disk full
This is the most common way to use it: the method cleans up after itself, and the caller decides what to do about the error.
Non-local exits
ensure also runs when control jumps out of a block with next, break or throw:
[1, 2, 3].each do |n|
next if n == 1
puts "processing #{n}"
break if n == 2
ensure
puts "ensure for #{n}"
end
result = catch(:done) do
begin
throw :done, 42
ensure
puts "ensure ran during throw"
end
end
p result
loop do
begin
break
ensure
puts "ensure ran during break"
end
end
ensure for 1
processing 2
ensure for 2
ensure ran during throw
42
ensure ran during break
Allowing ensure (and rescue) directly inside do ... end blocks was added in Ruby 2.5. It doesn't work in { ... } blocks; use begin ... end inside them.
Order of rescue, else and ensure
The full form has four parts, and they always appear in this order:
def run(fail)
puts "body"
raise "boom" if fail
rescue => e
puts "rescue: #{e.message}"
else
puts "else: no exception"
ensure
puts "ensure"
end
run(false)
puts "--"
run(true)
body
else: no exception
ensure
--
body
rescue: boom
ensure
else runs only if the body raised nothing; ensure runs last in every case. An exception raised inside rescue or else still triggers ensure.
The value of ensure is ignored
The result of a method or begin block comes from the body (or from rescue), never from the last expression in ensure:
def value
:from_body
ensure
:from_ensure
end
p value
:from_body
That's intentional: cleanup code like file.close shouldn't change what the method returns.
Don't use return in ensure
An explicit return inside ensure does change the result. Worse, it silently throws away any exception that is in flight:
def overrides
:from_body
ensure
return :from_ensure
end
p overrides
def swallow
raise "important error"
ensure
return :oops
end
p swallow
:from_ensure
:oops
swallow raised an error, but the caller sees a normal return value. The same happens with break or next in an ensure inside a block. Keep ensure to cleanup and never leave it with a jump.
Exceptions raised inside ensure
If the cleanup code itself raises, the new exception replaces the one that was propagating. Ruby keeps the original in cause, so it isn't lost entirely:
def cleanup_fails
raise "original problem"
ensure
raise "cleanup failed"
end
begin
cleanup_fails
rescue => e
puts "got: #{e.message}"
puts "cause: #{e.cause&.message}"
end
got: cleanup failed
cause: original problem
Error trackers usually show the cause, but code that rescues a specific class (say ActiveRecord::RecordInvalid) will no longer match. When cleanup can fail and the failure isn't important, rescue it inside ensure:
ensure
begin
conn&.close
rescue IOError => e
warn "close failed: #{e.message}"
end
end
Acquire outside, release inside
A very common bug is acquiring the resource inside the begin block:
def broken(path)
begin
file = File.open(path)
file.read
ensure
file.close
end
end
begin
broken("/no/such/file")
rescue => e
puts "#{e.class}: #{e.message}"
end
NoMethodError: undefined method 'close' for nil
File.open failed, so file is nil, and the NoMethodError from ensure hides the real error (Errno::ENOENT). Acquire the resource before begin, so ensure only runs once there's something to release:
def fixed(path)
file = File.open(path) # if this raises, there is nothing to close
begin
file.read
ensure
file.close
end
end
begin
fixed("/no/such/file")
rescue => e
puts "#{e.class}: #{e.message}"
end
Errno::ENOENT: No such file or directory @ rb_sysopen - /no/such/file
If you must acquire inside (for example in a method-level ensure), use safe navigation: file&.close.
Several resources
Each resource gets its own begin/ensure, nested in the order they're acquired, so they're released in reverse order and a failure to acquire the second one still releases the first:
def acquire(name)
puts "acquire #{name}"
name
end
def release(name) = puts("release #{name}")
def transfer
a = acquire(:source)
begin
b = acquire(:target)
begin
raise "transfer failed"
ensure
release(b)
end
ensure
release(a)
end
end
begin
transfer
rescue => e
puts e.message
end
acquire source
acquire target
release target
release source
transfer failed
When you have a variable number of resources, close them all even if one fails, and re-raise afterwards:
def close_all(resources)
errors = []
resources.reverse_each do |r|
r.close
rescue => e
errors << e
end
raise errors.first unless errors.empty?
end
Res = Struct.new(:name, :fail) do
def close
raise IOError, "#{name} close failed" if fail
puts "closed #{name}"
end
end
begin
close_all([Res.new("a"), Res.new("b", true), Res.new("c")])
rescue IOError => e
puts "error: #{e.message}"
end
closed c
closed a
error: b close failed
Knowing whether the block failed
ensure doesn't receive the exception, but you can tell success from failure with a flag set as the last step of the body. Inside ensure, $! holds the exception being propagated (or nil):
def work(fail)
success = false
raise "boom" if fail
success = true
ensure
puts success ? "commit" : "rollback (error: #{$!.inspect})"
end
work(false)
begin
work(true)
rescue
end
commit
rollback (error: #<RuntimeError: boom>)
The flag is more reliable than $! because it also catches a non-local exit like throw or return from the middle of the body. If you want to roll back only on errors, rescue => e; rollback; raise is clearer.
The block pattern: let the method clean up
Idiomatic Ruby rarely writes ensure for standard resources. Instead, methods that acquire something accept a block, yield the resource, and release it in their own ensure. You can't forget to close, and every way of leaving the block is covered:
require 'tmpdir'
Dir.mktmpdir do |dir|
src = File.join(dir, "in.txt")
File.write(src, "hello\n")
File.open(src) do |input|
File.open(File.join(dir, "out.txt"), "w") do |output|
output.write(input.read.upcase)
end
end
puts File.read(File.join(dir, "out.txt"))
Dir.chdir(dir) do
puts Dir.pwd == File.realpath(dir)
end
puts Dir.pwd == File.realpath(dir)
end
HELLO
true
false
Both files are closed, the working directory is restored after Dir.chdir, and the temporary directory is deleted with everything in it. Other block-form APIs in the standard library:
| Method | Cleanup it guarantees |
|---|---|
File.open(path) { }, IO.popen { } |
closes the file or pipe |
Dir.mktmpdir { } |
removes the directory recursively |
Tempfile.create { } |
closes and deletes the file |
Dir.chdir(dir) { } |
restores the previous directory |
Mutex#synchronize { } |
unlocks the mutex |
TCPSocket.open, Net::HTTP.start { } |
closes the connection |
File#flock + File.open { } |
lock released when the file closes |
Here's Tempfile.create next to its manual equivalent:
require 'tempfile'
path = Tempfile.create("report") do |f|
f.write("data")
f.path
end
p File.exist?(path)
tmp = Tempfile.create("manual")
begin
tmp.write("x")
ensure
tmp.close
File.unlink(tmp.path)
end
p File.exist?(tmp.path)
false
false
See Temporary files for more.
Writing your own
The same pattern works for your own resources. Return the object when there's no block, so callers can still manage it manually:
class Connection
def self.open(name)
conn = new(name)
return conn unless block_given?
begin
yield conn
ensure
conn.close
end
end
def initialize(name)
@name = name
puts "connect #{@name}"
end
def query(sql) = "result of #{sql}"
def close = puts("disconnect #{@name}")
end
rows = Connection.open("db1") { |c| c.query("SELECT 1") }
p rows
begin
Connection.open("db2") { |c| raise "query failed" }
rescue => e
puts "error: #{e.message}"
end
def first_row
Connection.open("db3") { |c| return c.query("SELECT 2") }
:not_reached
end
p first_row
connect db1
disconnect db1
"result of SELECT 1"
connect db2
disconnect db2
error: query failed
connect db3
disconnect db3
"result of SELECT 2"
The block's value becomes the method's value (that's why rows gets the query result), the exception reaches the caller after the connection is closed, and return from inside the block still disconnects.
Threads, timeouts and exit
ensure runs in more situations than plain exceptions:
lock = Mutex.new
begin
lock.synchronize { raise "failed while holding lock" }
rescue => e
puts e.message
end
p lock.locked?
t = Thread.new do
sleep
ensure
puts "thread cleanup"
end
sleep 0.1
t.kill
t.join
p t.status
require 'timeout'
begin
Timeout.timeout(0.1) do
sleep 1
ensure
puts "timeout cleanup"
end
rescue Timeout::Error => e
puts "timed out: #{e.message}"
end
failed while holding lock
false
thread cleanup
false
timeout cleanup
timed out: execution expired
Thread#killunwinds the thread and runs itsensureclauses (see How to kill a thread).Timeout.timeoutraises inside the block, soensureruns. The exception can arrive at any line, even halfway through your cleanup, which is why timeouts built into the library (open_timeout,read_timeout, database statement timeouts) are safer thanTimeout.- Ctrl+C raises
InterruptandexitraisesSystemExit, soensureruns for both, followed byat_exithandlers:
at_exit { puts "at_exit handler" }
begin
puts "exiting"
exit 1
ensure
puts "ensure still runs on exit"
end
exiting
ensure still runs on exit
at_exit handler
exit! ends the process immediately and skips both ensure and at_exit, as does kill -9. Ruby can't run cleanup code when the process is killed from outside, so anything that must survive a crash, like a half-written file, needs a different approach: write to a temporary file and rename it into place. For handling SIGTERM and similar signals see Signals and graceful shutdown.
Summary
ensureruns on normal completion, exceptions,return,break,next,throw,exit,Thread#killand timeouts, but notexit!orkill -9.- Its value is ignored; never
return,breakornextout of it, because that discards the exception in flight. - An exception raised in
ensurereplaces the original (available ascause); rescue cleanup errors that don't matter. - Acquire the resource before
begin, or use&.in cleanup, so a failed acquisition doesn't cause aNoMethodErroronnil. - Prefer block-form APIs (
File.open { },Mutex#synchronize,Tempfile.create { }) and give your own resource classes the same block-with-ensureinterface.