How to write trycatch in R

前端 未结 5 2221
灰色年华
灰色年华 2020-11-21 23:03

I want to write trycatch code to deal with error in downloading from the web.

url <- c(
    \"http://stat.ethz.ch/R-manual/R-devel/library/ba         


        
5条回答
  •  臣服心动
    2020-11-21 23:21

    tryCatch has a slightly complex syntax structure. However, once we understand the 4 parts which constitute a complete tryCatch call as shown below, it becomes easy to remember:

    expr: [Required] R code(s) to be evaluated

    error : [Optional] What should run if an error occured while evaluating the codes in expr

    warning : [Optional] What should run if a warning occured while evaluating the codes in expr

    finally : [Optional] What should run just before quitting the tryCatch call, irrespective of if expr ran successfully, with an error, or with a warning

    tryCatch(
        expr = {
            # Your code...
            # goes here...
            # ...
        },
        error = function(e){ 
            # (Optional)
            # Do this if an error is caught...
        },
        warning = function(w){
            # (Optional)
            # Do this if an warning is caught...
        },
        finally = {
            # (Optional)
            # Do this at the end before quitting the tryCatch structure...
        }
    )
    

    Thus, a toy example, to calculate the log of a value might look like:

    log_calculator <- function(x){
        tryCatch(
            expr = {
                message(log(x))
                message("Successfully executed the log(x) call.")
            },
            error = function(e){
                message('Caught an error!')
                print(e)
            },
            warning = function(w){
                message('Caught an warning!')
                print(w)
            },
            finally = {
                message('All done, quitting.')
            }
        )    
    }
    

    Now, running three cases:

    A valid case

    log_calculator(10)
    # 2.30258509299405
    # Successfully executed the log(x) call.
    # All done, quitting.
    

    A "warning" case

    log_calculator(-10)
    # Caught an warning!
    # 
    # All done, quitting.
    

    An "error" case

    log_calculator("log_me")
    # Caught an error!
    # 
    # All done, quitting.
    

    I've written about some useful use-cases which I use regularly. Find more details here: https://rsangole.netlify.com/post/try-catch/

    Hope this is helpful.

提交回复
热议问题