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

Error handling (tryCatch)

This lesson covers error handling with R's tryCatch, with the aim of keeping a program running even when something unexpected goes wrong.

tryCatch() catches an error so the whole program does not stop. Think of it as insurance: deciding in advance what to do instead, should something fail.

In the sample code, a divide() function raises an error with stop() on division by zero, and tryCatch({...}, error = function(e) {...}) catches it. Note how conditionMessage(e) pulls the error message out.

A common early stumble is tryCatch's distinctive syntax. It plays the same role as try-catch elsewhere, but writing it as a function — the body in braces, the handler passed as error = function(e) {} — takes some getting used to.

In professional work, tryCatch is used around anything that can fail, such as reading data or talking to an external service.

๐Ÿ“– 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)