The ensure
of Ruby is equivalent to finally
of other languages: it defines a block of code that will always be executed, either after the begin
, is after catching an exception.
begin
puts 'Bloco de código que será tentado executar'
raise 'Algo errado não está certo'
rescue Exception
puts 'É, algo saiu errado'
ensure
puts 'Esse trecho sempre será executado'
end
See working on Repl.it
The exit would be:
Bloco de código que será tentado executar
É, algo saiu errado
Esse trecho sempre será executado
If there wasn’t the raise
inside the block in begin
, the block in rescue
would not be executed, only the ensure
:
begin
puts 'Bloco de código que será tentado executar'
rescue Exception
puts 'É, algo saiu errado'
ensure
puts 'Esse trecho sempre será executado'
end
Producing the output:
Bloco de código que será tentado executar
Esse trecho sempre será executado
It is a useful tool when you need to guarantee (hence the name ensure
, ensure in English) that a particular piece of code is executed whether there is a fault or not. A hypothetical example would be, for example, in managing communication with the database and transactions:
begin
db = Database.new
db.connect
db.transaction.start
db.persist(entity)
db.transaction.commit
rescue Exception
db.transaction.rollback
ensure
db.close
end
Thus, failing or not the persistence of the data in the database, the connection would be properly closed.
Other readings:
This seems to be an exercise statement. If so, how do you think the answer is? How would you describe the function of
ensure
?– Woss
I’m studying this site here: https://www.tutorialspoint.com/ruby/ruby_exceptions.htm But it’s not clear about 'ensure' in exceptions.
– user110265