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
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. x
and then try to get the sum it also results in a NaN
.do_calculation
function to the following: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.error
as another parameter to catch errors intead of warnings.