Ad space (banner)
๐Ÿ“ŠR Lessons
Lesson 50 / 68

Cleaning up with tryCatch's finally

This lesson covers cleanup with the finally part of R's tryCatch, with the aim of running something whether or not an error occurred.

A finally block always runs, error or no error. 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 error = function(e) {...} and always shows "Ending the calculation" from finally = {...}, error or not.

A common early stumble is the complexity of R's tryCatch() syntax. Passing the body, the error handler, and the cleanup as separate arguments takes some getting used to.

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 R 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)