Ad space (banner)
๐ŸŸฃJulia Lessons
Lesson 50 / 68

Cleaning up with try / catch / finally

This lesson covers cleanup with Julia's try / catch / finally, with the aim of running something whether or not an error occurred.

A finally block always runs, exception or no exception. Use it to close a file or to signal that work has finished.

In the sample code, divide() catches a division-by-zero error with catch e and always shows "Ending the calculation" from the finally block, error or not. Note how e.msg pulls the error message out.

A common early stumble is when finally runs. Even if the try block returns, finally runs first — miss that ordering and the flow is easy to misread.

In professional work, finally is used wherever an external resource such as a file or a database connection has been opened and must reliably be closed, however things end.

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

๐Ÿงช This site can't compile or run Julia 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)