0
0
R Programmingprogramming~20 mins

Error handling (tryCatch) in R Programming - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
tryCatch Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this tryCatch example?
Consider the following R code using tryCatch. What will be printed when it runs?
R Programming
result <- tryCatch({
  stop("Error happened")
  10
}, error = function(e) {
  "Caught error"
})
print(result)
A[1] 10
BNULL
CError in stop("Error happened"): Error happened
D[1] "Caught error"
Attempts:
2 left
💡 Hint
Remember that stop() causes an error and tryCatch handles it.
Predict Output
intermediate
2:00remaining
What does this tryCatch return when no error occurs?
Look at this R code. What is the value of 'result' after running?
R Programming
result <- tryCatch({
  5 + 3
}, error = function(e) {
  0
})
print(result)
AError in 5 + 3 : non-numeric argument to binary operator
B[1] 0
C[1] 8
DNULL
Attempts:
2 left
💡 Hint
No error is triggered in the expression 5 + 3.
Predict Output
advanced
2:00remaining
What error does this code raise?
What error message will this R code produce?
R Programming
tryCatch({
  log("a")
}, error = function(e) {
  stop("Custom error")
})
AError: Custom error
BWarning message: In log("a") : NaNs produced
CNULL
DError in log("a"): non-numeric argument to mathematical function
Attempts:
2 left
💡 Hint
The error handler re-throws a new error with stop().
🧠 Conceptual
advanced
2:00remaining
Which option correctly catches warnings with tryCatch?
You want to catch warnings in R using tryCatch. Which code snippet correctly catches a warning?
AtryCatch({ warning("Watch out!") }, warning = function(w) { print("Warning caught") })
BtryCatch({ warning("Watch out!") }, error = function(e) { print("Warning caught") })
CtryCatch({ warning("Watch out!") }, finally = function(f) { print("Warning caught") })
DtryCatch({ warning("Watch out!") }, message = function(m) { print("Warning caught") })
Attempts:
2 left
💡 Hint
Use the 'warning' argument to catch warnings.
🔧 Debug
expert
2:00remaining
Why does this tryCatch not catch the error?
This R code does not catch the error as expected. What is the reason?
R Programming
tryCatch({
  stop("Fail")
}, warning = function(w) {
  print("Warning caught")
})
Astop() does not generate an error, so tryCatch does nothing.
BThe error handler is missing; only warning handler is defined, so error is not caught.
CThe warning handler catches errors too, so this should work.
DtryCatch requires a finally block to catch errors.
Attempts:
2 left
💡 Hint
stop() triggers an error, not a warning.