1 Goal


The goal of this tutorial is to understand some basic use of the try function. Sometimes we need to be able to handle errors in functions because the error is just information that something went wrong.


2 The try function


# The try function returns the output of a regular expression if the result was successful 
# If there was an error the result is an object of class try-error that contains information about what happened
# The parameter silent = TRUE allows us to carry on with the script ignoring the errors


# We can use a regular expression
x <- 10
x < 5
## [1] FALSE
# Now we can use this expression inside of a try function in order to be able to recover from possible errors
try(x < 5)
## [1] FALSE
# We see that the generated object is of class bool and FALSE
str(try(x < 5))
##  logi FALSE
# In this example the object z does not exist, so the code should break at this point
# We use silent = TRUE to keep going
try(z< 5, silent = TRUE)

# The generated object contains all the information regarding the error 
str(try(z< 5, silent = TRUE))
## Class 'try-error'  atomic [1:1] Error in try(z < 5, silent = TRUE) : object 'z' not found
## 
##   ..- attr(*, "condition")=List of 2
##   .. ..$ message: chr "object 'z' not found"
##   .. ..$ call   : language doTryCatch(return(expr), name, parentenv, handler)
##   .. ..- attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
# Now we see that the class of the object generated is try-error
class(try(z< 5, silent = TRUE))
## [1] "try-error"

3 How to use the try function


# We can use the try function to create safety checks to make our code more robust

if(class(try(z < 5, silent = TRUE)) == "try-error"){
  print(try(z < 5, silent = TRUE)[1])
}else{
  print(paste("z < 5 is ", try(z < 5)))
}
## [1] "Error in try(z < 5, silent = TRUE) : object 'z' not found\n"
# Now we do the same example with x that exists in this tutorial
if(class(try(x < 5, silent = TRUE)) == "try-error"){
  print(try(x < 5, silent = TRUE)[1])
}else{
  print(paste("x < 5 is ", try(x < 5)))
}
## [1] "x < 5 is  FALSE"

4 Conclusion


In this tutorial we have learnt how to handle errors using the try function. This allows us to create more robusts and safe scripts.