Complete the code to catch errors using tryCatch.
result <- tryCatch({
log('a')
}, error = function(e) {
[1]
})The error argument in tryCatch defines a function to run when an error occurs. Using print('Error caught!') will display the message when the error happens.
Complete the code to return a default value when an error occurs.
safe_log <- function(x) {
tryCatch(log(x), error = function(e) [1])
}
safe_log('a')Returning NA is a common way to indicate a missing or invalid result when an error occurs.
Fix the error in the tryCatch usage to properly handle warnings.
result <- tryCatch({
sqrt(-1)
}, warning = function(w) {
[1]
})The warning handler function should print a message or handle the warning gracefully. Using print('Warning caught!') shows the warning was caught.
Fill both blanks to catch errors and return a message.
result <- tryCatch({
log('a')
}, error = function(e) {
[1]
}, finally = {
[2]
})The error handler returns a message string. The finally block runs cleanup code, here printing a message.
Fill all three blanks to catch errors, warnings, and run final code.
result <- tryCatch({
log(-10)
}, error = function(e) {
[1]
}, warning = function(w) {
[2]
}, finally = {
[3]
})The error handler returns NA to handle errors gracefully. The warning handler prints a message. The finally block prints a cleanup message.