Analytics Vidhya
Published in

Analytics Vidhya

Error Handling in R

What is an Exception?

An unwanted situation that may arise while your code is getting exected is called an Exception e.g when your code attempts to divide a value by zero.

Exception Handling

Exception handling is the process of handling the errors that might occur in the code and avoid abrupt halt of the code. In simple English, our code should either end by performing the intended task or prints a useful message if it is not able to complete the task.

We have this code which has non-numeric value in the list and we are trying to divide 5 with every element of vector v

#list with one non numeric value v<-list(1,2,4,’0',5) for (i in v) { print(5/i) }

Here we can see that the code has not printed any result and has stopped abruptly.

To avoid these situations we use exception handling constructs available in R

Exception Handling Constructs in R

  1. try
  2. tryCatch

Using try

We need to enclose the objectionable statements in the try block. The statements passed inside are like arguments to a function. In case you have more than one statements, it is preferred that you write a function with all those statements and call the function inside the try block

for (i in v) {

Using the try block we can see the code ran for all the other cases even after the error in one of the iteration.

Using tryCatch

The try block will not let your code stop but does not provide any mechanism to handle the exception. By handling I mean the actions we want to perform if some error occurs in code execution.

In this case, we can use the tryCatch block to handle the exception.

We will enclose the objectionable statement in the tryCatch block and pass one more parameter to the tryCatch, error.

The error takes as input a function or an instruction and we can perform all the remedial steps to be performed in case of an error in this function.

for (i in v) {
print("Non conformabale arguments")

I hope this helps you in understanding the error handling concepts in R.

You might also want to read:

Subscribe to Techscouter for updates on articles related to ML, Data Mining, Programming languages, and current market trends.

Author: Japneet Singh

Happy Learning



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store