tryCatchfunction 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_calculationthat 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
NaNand a warning. This function represents a function with some stocastic probability to sometimes fail.
xand then try to get the sum it also results in a
do_calculationfunction to the following:
tryCatchstatement. The first argument is the expression to evaluate and the
warningparameter 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.
erroras another parameter to catch errors intead of warnings.