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.
Contact Us