0
0
R Programmingprogramming~10 mins

Error handling (tryCatch) in R Programming - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to catch errors using tryCatch.

R Programming
result <- tryCatch({
  log('a')
}, error = function(e) {
  [1]
})
Drag options to blanks, or click blank then click option'
Awarning('Error caught!')
Blog(1)
Cprint('Error caught!')
Dstop('Error caught!')
Attempts:
3 left
💡 Hint
Common Mistakes
Using stop() inside the error handler will re-throw the error.
Not defining a function for the error argument.
Using warning() instead of print() does not stop the error.
2fill in blank
medium

Complete the code to return a default value when an error occurs.

R Programming
safe_log <- function(x) {
  tryCatch(log(x), error = function(e) [1])
}

safe_log('a')
Drag options to blanks, or click blank then click option'
AInf
BNULL
C0
DNA
Attempts:
3 left
💡 Hint
Common Mistakes
Returning NULL can cause issues if the caller expects a numeric value.
Returning 0 or Inf may mislead the user about the result.
3fill in blank
hard

Fix the error in the tryCatch usage to properly handle warnings.

R Programming
result <- tryCatch({
  sqrt(-1)
}, warning = function(w) {
  [1]
})
Drag options to blanks, or click blank then click option'
Aprint('Warning caught!')
Bstop('Warning caught!')
Creturn(NA)
Dmessage('Warning caught!')
Attempts:
3 left
💡 Hint
Common Mistakes
Using stop() inside warning handler re-throws the warning as an error.
Using message() may not be visible depending on console settings.
4fill in blank
hard

Fill both blanks to catch errors and return a message.

R Programming
result <- tryCatch({
  log('a')
}, error = function(e) {
  [1]
}, finally = {
  [2]
})
Drag options to blanks, or click blank then click option'
Areturn('Error handled')
Bprint('Cleaning up')
Cstop('Error handled')
Dmessage('Cleaning up')
Attempts:
3 left
💡 Hint
Common Mistakes
Using stop() in error handler re-throws the error.
Using message() in finally may not always show output.
5fill in blank
hard

Fill all three blanks to catch errors, warnings, and run final code.

R Programming
result <- tryCatch({
  log(-10)
}, error = function(e) {
  [1]
}, warning = function(w) {
  [2]
}, finally = {
  [3]
})
Drag options to blanks, or click blank then click option'
Areturn(NA)
Bprint('Warning caught')
Cprint('Cleaning up')
Dstop('Error caught')
Attempts:
3 left
💡 Hint
Common Mistakes
Using stop() in error handler causes the program to stop.
Not printing messages in warning or finally blocks hides useful info.