Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 50 / 68

Cleanup Logic with begin/rescue/ensure

In this lesson you will learn to write cleanup logic with begin/rescue/ensure so certain work always runs whether or not an error occurred. This is for anyone searching for "Ruby ensure how to use".

An ensure block is a cleanup block that always runs, whether an exception was raised or not (it corresponds to finally in other languages). Use it to close files or announce that processing has finished.

The sample code adds an ensure to the begin calculation and rescue error handling inside divide, always printing "Ending the calculation". Notice how the message appears both in the successful case and in the failing one.

A common stumbling block for beginners is writing a return inside ensure. Doing so overwrites the value the begin block was going to return, which can lead to behaviour you did not intend.

Cleanup such as closing a file or ending a connection has to happen regardless of errors. ensure is common wherever a resource must be released reliably, such as database connections and file handling.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)