Using tryCatch Function to Handle Errors & Warnings in R (3 Examples)

 

In this article you’ll learn how to debug R codes using the tryCatch function in the R programming language.

The tutorial will consist of this content:

Let’s start right away:

 

Basic Explanation of the tryCatch() Function

The tryCatch function checks whether an R code leads to an error or warning message. Hence, the tryCatch function is often used to debug R codes.

Within the tryCatch function, we usually should specify four arguments:

  • expr: This specifies the expression we want to evaluate.
  • error: The message we want to return in case of an error.
  • warning: The message we want to return in case of a warning.
  • finally: The message we want to return when the tryCatch function is finished.

Note that only the expr argument is mandatory. However, I recommend to specify the other arguments as well to produce meaningful outputs in case an error or warning message appears.

Let’s do this in practice…

 

Example 1: Executing tryCatch() Function without Warnings or Errors

The following example shows how to apply the tryCatch function to a properly specified expression in R. For this, we are using the expression 1 + 1.

tryCatch(                       # Applying tryCatch
 
  expr = {                      # Specifying expression
    1 + 1
    message("Everything was fine.")
  },
 
  error = function(e){          # Specifying error message
    message("There was an error message.")
  },
 
  warning = function(w){        # Specifying warning message
    message("There was a warning message.")
  },
 
  finally = {                   # Specifying final message
    message("tryCatch is finished.")
  }
)
# Everything was fine.
# tryCatch is finished.

The RStudio console returns the messages “Everything was fine.” and “tryCatch is finished.”, indicating that our expression didn’t have any problems.

 

Example 2: Executing tryCatch() Function with Error

The following syntax shows the application of tryCatch to a falsely specified expression. Let’s assume that we are trying to execute the expression 1 + “1” (i.e. the second “1” has the character class). Then, the tryCatch function returns the following output:

tryCatch(                       # Applying tryCatch
 
  expr = {                      # Specifying expression
    1 + "1"
    message("Everything was fine.")
  },
 
  error = function(e){          # Specifying error message
    message("There was an error message.")
  },
 
  warning = function(w){        # Specifying warning message
    message("There was a warning message.")
  },
 
  finally = {                   # Specifying final message
    message("tryCatch is finished.")
  }
)
# There was an error message.
# tryCatch is finished.

“There was an error message.” – We clearly have done something wrong in our R code.

Note that, for the sake of simplicity of this example, we are only returning a message to the RStudio console telling us that an error occurred.

However, you may use much more complex R codes to handle errors with the tryCatch function. You simply need to replace the error argument by the handler you want to use.

 

Example 3: Executing tryCatch() Function with Warning

Similar to the previous example, Example 3 shows how to apply the tryCatch command to an expression that returns a warning message. For this example, we’ll use the expression 1:2 + 1:3.

tryCatch(                       # Applying tryCatch
 
  expr = {                      # Specifying expression
    1:2 + 1:3
    message("Everything was fine.")
  },
 
  error = function(e){          # Specifying error message
    message("There was an error message.")
  },
 
  warning = function(w){        # Specifying warning message
    message("There was a warning message.")
  },
 
  finally = {                   # Specifying final message
    message("tryCatch is finished.")
  }
)
# There was a warning message.
# tryCatch is finished.

This time the tryCatch function returned our manually specified warning message.

 

Video & Further Resources

Do you want to know more about tryCatch? Then you may have a look at the following video tutorial of my YouTube channel. In the video instruction, I’m illustrating the R syntax of the present tutorial.

 

The YouTube video will be added soon.

 

Furthermore, you might read the related articles of this website.

 

In this article, I illustrated how to write a tryCatch in the R programming language. Let me know in the comments, in case you have any additional questions.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


4 Comments. Leave new

  • The expression like:

    warning = function(w){
    message(w$message)

    returns warning and error messages

    Reply
  • I am not sure if it is important. But sometimes it is necessary to see what exactly was wrong:
    Input:

    tryCatch( # Applying tryCatch

    expr = { # Specifying expression
    1 + ‘u’
    message(“Everything was fine.”)
    },

    error = function(e){ # Specifying error message
    message(e$message)
    },

    warning = function(w){ # Specifying warning message
    message(w$message)
    },

    finally = { # Specifying final message
    message(“work is finished.”)
    }
    )

    Output:

    non-numeric argument to binary operator
    work is finished.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top