TryCatch

So the tryCatch function in R allows you to try run piece of code and if it gives a warining or error, to do something else instead of crashing. Lets take this example:

do_calculation<-function(){
  int<-sample(c(-1,1),1)
  sqrt(int)
}

x = c()
for (i in 1:10){
  x<-c(x,do_calculation())
}

sum(x)

We have a function do_calculation that returns the quare root of some number. It will randomly sample either 1 or -1. Trying to return the square root of -1 will result in the function returning a NaN and a warning. This function represents a function with some stocastic probability to sometimes fail.

If we iterate this function a couple of times, store it in vector x and then try to get the sum it also results in a NaN.

Now lets try catch the error before it return a NaN and rerun the function. Change you do_calculation function to the following:

do_calculation<-function(){
  int<-sample(c(-1,1),1)
  tryCatch({
    sqrt(int)
  }, warning=function(w){
    do_calculation()
  })
}

We have replaced sqrt(int) with a tryCatch statement. The first argument is the expression to evaluate and the warning parameter allows you to fun some code when we get a warning. In out case we just want to run the function again, in the hope of sampling 1 instead of -1. Now when we run the function a few times we should be able to see that it always returns 1.

You can also add error as another parameter to catch errors intead of warnings.

Last updated