Error Handling in R Programming

Syntax Error

# Syntax Error Example
# This code contains a syntax error due to a missing closing parenthesis
print("Hello, world!")  # Corrected: Added the missing closing parenthesis

Output:

[1] "Hello, world!"

Runtime Error

# Define a function to perform division
safe_division <- function(x, y) {
  tryCatch(
    {
      result <- x / y
      if(is.infinite(result)){
        return("Error: Division by zero occurred.")
      } else {
        return(result)
      }
    },
    error = function(e) {
      return("Error: Division by zero occurred.")
    }
  )
}

# Example usage
result <- safe_division(10, 0)
print(result) # This will print "Error: Division by zero occurred."

Output:

[1] "Error: Division by zero occurred."

Logical Error

# Logical Error Example
# This code attempts to add two strings together, resulting in a logical error
# Corrected: Using paste() function to concatenate strings
result <- paste("Hello", "World")  
print(result)

Output:

[1] "Hello World"


How to Implement Error Handling in R Programming

Error handling is a crucial aspect of programming that allows to identify, and gracefully manage errors or exceptions that may occur during the execution of code. In R Programming Language, effective error handling can enhance the reliability of scripts and applications.

Similar Reads

What are Errors in R?

An error refers to a condition that occurs when the execution of a statement or function encounters a problem that prevents it from completing successfully. Good error handling helps to deal with errors and gives helpful messages to users....

Cause of Error

Syntax Error: The code doesn’t follow the right structure. For instance, if we write print(“Hello, world!”) but forget to close the quotation marks, we’ll see a syntax error....

Error Handling in R Programming

Syntax Error...

Contact Us