Skip to content

Throw From Finally (ARCH6155)

Key ruby.logging.raise-in-ensure · Severity error · Category logging

Raising inside an ensure block masks any in-flight exception from the begin body and loses the real failure. Cleanup code must not raise.

def write(file)
file.write(data)
ensure
raise "Could not close stream" unless file.close
end
def write(file)
file.write(data)
ensure
begin
file.close
rescue => e
Rails.logger.warn("Could not close stream", exception: e)
end
end

Catch and log cleanup errors inside the ensure block; do not raise from there.