TryCatch: Why is the warning handled as an error?

Why does the following code not return 2, but treat the warning as an error?

tryCatch({
  1+1
  warning("test")
  return(2)
}, error=function(e){
  print("error")
}, finally = {})

[1] "error"
Warning message:
In doTryCatch(return(expr), name, parentenv, handler) : test

How can I handle errors but ignore warnings?

+4
source share
1 answer

While you manually run warning, your expression also throws an error because you are using returnoutside the function.

This becomes more apparent if you return the error message itself in function(e)(instead of typing "error"):

tryCatch({
  1+1
  warning("test")
  return(2)
}, error=function(e) {
  e
})

# <simpleError in doTryCatch(return(expr), name, parentenv, handler): 
#  no function to return from, jumping to top level>
# Warning message:
# In doTryCatch(return(expr), name, parentenv, handler) : test

(Note that this is equivalent to throwing an argument error.)

, , return(2) R:

return(2)
# Error: no function to return from, jumping to top level

, return , :

tryCatch({
  1+1
  warning("test")
  2
}, error=function(e){
  print('error')
})

# [1] 2
# Warning message:
# In doTryCatch(return(expr), name, parentenv, handler) : test
+6

All Articles