Tutorials

Search…

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:1

do_calculation<-function(){

2

int<-sample(c(-1,1),1)

3

sqrt(int)

4

}

5

6

x = c()

7

for (i in 1:10){

8

x<-c(x,do_calculation())

9

}

10

11

sum(x)

Copied!

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:1

do_calculation<-function(){

2

int<-sample(c(-1,1),1)

3

tryCatch({

4

sqrt(int)

5

}, warning=function(w){

6

do_calculation()

7

})

8

}

Copied!

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 modified 1yr ago

Copy link