How to Use trycatch in R to Prevent Errors From Stopping Your Code

The most annoying thing about writing computer code, and the one thing more than any other that temps a programmer to shoot his computer is getting error messages. Furthermore. Now when you are writing the code, the best way to deal with an error message at that stage is to fix it. Unfortunately, you cannot always anticipate every thing that the user of your program may do. Because of this, it is helpful to have one or more functions that are designed to catch and handle errors and warnings during execution without stopping the program, and that is where the trycatch function comes into play.


The trycatch function is designed to take care of error handling. Within R the trycatch function sets up the code for exception handling so that even if your user does something really crazy that you cannot foresee, they will not be as likely to crash the program than they would have been without it. By embedding an operation within this particular function it keeps both errors and warnings from interrupting your program. If the operation that you use with the trycatch function triggers an error or a warning it gives you control over the error message that the program displays if any. In fact, if you do not think that the user needs to know then you do not have to do anything, or you may even be capable of correcting the problem without them even knowing about it. Now, the trycatch function should not be used to avoid debugging your program while you are writing it, but it is helpful to deal with errors and warnings that may occur because of user input or other data.


The trycatch function has three different blocks. It starts out with the try block where are you find the statement you are trying to catch, this can be functions, mathematical statements or just about any code you suspect could trigger an error or a warning under circumstances that are out of your control. This is followed by the catch block were you trying to catch and if necessary, deal with errors or warnings that show up when the program is running. The catch block uses a handler function that finds the error or warning message that is generated. In this block you can also set return values for each of the possible results that you can catch. The finally block is an ending section, that gives you an opportunity to tie up any loose ends before leaving.


Here are several examples the trycatch function in action. We provide a total of three examples. the first is extremely simple, the second catches more than one situation, and the third is a complex example that uses a multiple catch block.

> x = log(“cat”)
Error in log(“cat”) : non-numeric argument to mathematical function

This first example does not try to catch the errors but merely shows to results she would get without trying to do so.

> tryCatch(log(“cat”),
+ error = function(e)
+ print(“A character does not have a log”))
[1] “A character does not have a log”

This first example simply uses try-catch to catch the arguments error, in the simple possible demonstration of the try-catch in action. It is so simple that it only has the try block and a simple catch block.

> tryCatch(
+ {x = log(“cat”)
+ x},
+ error = function(e)
+ print(“The variable x is empty.”),
+ print(“A character does not have a log”))
[1] “A character does not have a log”
[1] “The variable x is empty.”

Here we have an example of trying to catch errors from two different statements. Note that it has two statements in the tri block and two in the catch block. This makes it more complicated, but it is still relatively simple because it does not check for warnings as well.

> ld = function(x, y){
+ tryCatch(
+ {
+ result = log(x) / y
+ return(result)
+ },
+ error=function(e) {
+ message(‘Error’)
+ },
+ warning=function(w) {
+ message(‘Warning’)
+ return(NA)},
+ finally = { message(“end.”)}
+ )}
> ld(20, 5)
[1] 0.5991465
> ld(20)
> ld(-20, 5)
[1] NA

Here we have an example that has a multiple catch block, that catches both error and warning messages. It also has a simple finally block to illustrate that part of the process. This case is embedded in another function so that it can illustrate all three possible results.


The most common application of the trycatch function and error handling functions is protecting the program from the user. This may sound funny at first but when you think about it the user is the one untestable variable that a programmer has. You can test your coding for every conceivable mistake that you could have made. You can test it for every possible inconsistency, or other coding problems. However, you cannot possibly anticipate everything the user may do. It is always possible that without an error-handling routine, some users will cause a glitch, because they did something, that you could not anticipate, and it did not show up in the code. Because you cannot anticipate everything, functions such as try-catch make your program prepared for almost anything a user can throw at it.

Handling errors and warnings are an important part of any computer program. Unfortunately, you cannot fix everything, because there are some situations that cannot be fixed by coding because they do not originate from coding mistakes. The user is the number one cause of problems with a program that the programmer cannot control. Handling errors and warnings within the program are the way to handle this problem. Without it sooner or later, a user is likely to enter something that causes an error or warning, Forms of exception handling help you to deal with potential problems that you can not anticipate nor control if you could.

Scroll to top