Write R code for a function called safe_sqrt that takes a number as input and returns its square root. If a negative number is provided, it should print "Cannot take square root of negative number" instead of throwing an error.
Even experienced programmers encounter errors. R provides tools to find and fix problems in your code. Proper error handling ensures your scripts run smoothly even when unexpected data or situations occur.
# Example of a function with a potential error
divide <- function(a, b) {
a / b
}
# Debug the function
debug(divide)
divide(10, 0)
This function takes two numbers, a
and b
, and divides a
by b
. The issue is that dividing by zero (b = 0
) will cause an error.
debug(divide)
tells R to step through the divide
function line by line when it runs.divide(10, 0)
now pauses execution so you can inspect variables and see exactly where the problem occurs. This is useful for troubleshooting errors.# Using tryCatch to handle errors
safe_divide <- function(a, b) {
tryCatch({
result <- a / b
result
}, warning = function(w) {
print("Warning occurred")
}, error = function(e) {
print("Error: Division by zero")
})
}
safe_divide(10, 0)
This new function, safe_divide
, uses tryCatch
to run the division safely:
"Warning occurred"
."Error: Division by zero"
instead of crashing the program.Here, dividing 10 by 0 would normally stop execution with an error. But with tryCatch
, the function prints a friendly error message and continues running smoothly.
Debugging and error handling help make your R scripts more robust and reliable.