Disregarding simple warnings/errors in tryCatch()

后端 未结 2 2009
南旧
南旧 2020-12-05 06:00

I\'m a huge fan of tryCatch(). However, until today I never really paid attention to the distinction between simple and regular warnings/errors and thus I don\'

相关标签:
2条回答
  • 2020-12-05 06:38

    I think you're looking for the difference between tryCatch, which catches a condition and continues evaluation from the environment where the tryCatch was defined, versus withCallingHandlers, which allows you to 'handle' a condition and then continue on from the location where the condition occurred. Take a look at warning (or the help page for warning, but that's less fun), especially the lines

        withRestarts({
            .Internal(.signalCondition(cond, message, call))
            .Internal(.dfltWarn(message, call))
        }, muffleWarning = function() NULL)
    

    This says -- signal a condtion, but insert a 'restart' where the condition was signaled from. Then you'd

    withCallingHandlers({
        warning("curves ahead")
        2
    }, warning = function(w) {
        ## what are you going to do with the warning?
        message("warning occurred: ", conditionMessage(w))
        invokeRestart("muffleWarning")
    })
    

    Although withCallingHandlers is often used with warnings and tryCatch with errors, there is nothing to stop one from 'handling' an error or catching a warning if that is the appropriate action.

    0 讨论(0)
  • 2020-12-05 06:38

    You can recall the forecast within the warning section, something like this:

    mod <- tryCatch(
      out <- forecast::auto.arima(x=y),
      error=function(e) {
        print(e)
      },
      warning=function(w) {
        print(w)
        out <- forecast::auto.arima(x=y)
        return(out)
      }
    )
    

    This will print a warning , but the result of forecast is stored in mod now.

    <simpleWarning in kpss.test(x): p-value smaller than printed p-value>
    > mod
    Series: y 
    ARIMA(4,1,1)                    
    
    Coefficients:
             ar1      ar2     ar3      ar4      ma1
          0.6768  -0.2142  0.5025  -0.7125  -0.8277
    s.e.  0.0749   0.0889  0.0874   0.0735   0.0485
    
    sigma^2 estimated as 915556:  log likelihood=-780.33
    AIC=1572.65   AICc=1573.62   BIC=1587.91
    
    0 讨论(0)
提交回复
热议问题