Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch specific warning and ignore others [duplicate]

Tags:

r

try-catch

I'm debugging some code which gives several warnings, but I'm trying to stop the code when I receive a specific warning so I can look at the environment.

For example:

myfun <- function(){
  warning("The wrong warning")
  warning("The right warning")
  print("The end of the function")
}

tryCatch(myfun(),
         warning = function(w){
           if(grepl("right", w$message)){
             stop("I have you now")
           } else {
             message(w$message)
           }
         })

What I'd like to happen is for the function to stop at "The right warning", but the catch stops as soon as it receives its first warning. How can I skip over warnings that aren't of interest and stop on the ones that interest me?

like image 904
sebastian-c Avatar asked May 04 '16 16:05

sebastian-c


People also ask

How do I ignore a warning in Python?

Use the filterwarnings() Function to Suppress Warnings in Python. The warnings module handles warnings in Python. We can show warnings raised by the user with the warn() function. We can use the filterwarnings() function to perform actions on specific warnings.

Which of the following modules warn about common sources of errors present in Python script?

Warning messages are displayed by warn() function defined in 'warning' module of Python's standard library. Warning is actually a subclass of Exception in built-in class hierarchy.

How do you print a warning message in Python?

The warn() function defined in the ' warning ' module is used to show warning messages. The warning module is actually a subclass of Exception which is a built-in class in Python. print ( 'Geeks !' )


1 Answers

I believe withCallingHandlers is what you want: Disregarding simple warnings/errors in tryCatch()

withCallingHandlers(myfun(),
   warning = function(w){
     if(grepl("right", w$message)){
       stop("I have you now")
     } else {
       message(w$message)
     }
   })
like image 51
fanli Avatar answered Nov 15 '22 05:11

fanli