简体   繁体   中英

Move to the next code line if failed In R

I don't know how to search it on Google. I have a code of lines that are independent of each other - suppose one line fails for some reason then the rest of the script does not continue. How do I make it continue?

For example:

library(RODBC)
library(sqldf)
myconn<-odbcConnect("production")

#line 1: sqlQuery(myConn,"exec sp_v_table_1")

#line 2: sqlQuery(myConn,"exec sp_v_table_2")

Failed too because line 1 failed

In addition, how do I know that a certain code line - For example :

sqlQuery(myConn,"exec sp_v_table_3") 

has passed successfully and not failed?

You could use tryCatch block, you have a reference here

Here you have an example using it for a request handling:

urls <- c(
"http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html",
"http://en.wikipedia.org/wiki/Xz",


   "xxxxx"
)

readUrl <- function(url) {
    out <- tryCatch(
        {
            # Just to highlight: if you want to use more than one 
            # R expression in the "try" part then you'll have to 
            # use curly brackets.
            # 'tryCatch()' will return the last evaluated expression 
            # in case the "try" part was completed successfully
        message("This is the 'try' part")

        readLines(con=url, warn=FALSE) 
        # The return value of `readLines()` is the actual value 
        # that will be returned in case there is no condition 
        # (e.g. warning or error). 
        # You don't need to state the return value via `return()` as code 
        # in the "try" part is not wrapped insided a function (unlike that
        # for the condition handlers for warnings and error below)
    },
    error=function(cond) {
        message(paste("URL does not seem to exist:", url))
        message("Here's the original error message:")
        message(cond)
        # Choose a return value in case of error
        return(NA)
    },
    warning=function(cond) {
        message(paste("URL caused a warning:", url))
        message("Here's the original warning message:")
        message(cond)
        # Choose a return value in case of warning
        return(NULL)
    },
    finally={
    # NOTE:
    # Here goes everything that should be executed at the end,
    # regardless of success or error.
    # If you want more than one expression to be executed, then you 
    # need to wrap them in curly brackets ({...}); otherwise you could
    # just have written 'finally=<expression>' 
        message(paste("Processed URL:", url))
        message("Some other message at the end")
    }
)    
return(out)
}

The source is from this stackoverflow response, which I obviously recommend you to take look.

Use the try command.

Normally this will cause an error and prevent code that comes afterwards from running:

x <- "a" + 1
y <- 1
y

However, if we wrap the part after the assignment operator in try , the error prints but code written afterwards can still run:

x <- try("a" + 1)
y <- 1
y

Note that x has class "try-error"

class(x)
"try-error"

Therefore in your example, you could do the following to make sure later lines run whilst still being able to pick up that earlier lines failed:

x <- try(sqlQuery(myConn,"exec sp_v_table_3"))
y <- 1
y
class(x) 

The object y will still be created, and the class of x will tell you whether sqlQuery(myConn,"exec sp_v_table_3") ran successfully or not.

tryCatch is in a sense a more flexible version of try . try will only return class "try-error" if an error occurs and allow later lines of code to run, but tryCatch will allow you to specify what you want to happen if an error occurs. You could also specify what you want to happen if a warning occurs or even if the code runs successfully.

And purrr::safely is a wrapper around tryCatch . There the action specified upon an error is to return a list with two elements: alternate output (by default NULL ) and the error message.

You need a way to capture the error. A tool I appreciate for thus purpose is safely() from the purrr package.

Your wrap a function around your existing function call, that safely returns an output, even when an error occurs.

From the documentation (log() example) :

safe_log <- safely(log)
safe_log(10)
#> $result
#> [1] 2.302585
#> 
#> $error
#> NULL
#> 
safe_log("a")
#> $result
#> NULL
#> 
#> $error
#> <simpleError in .Primitive("log")(x, base): non-numeric argument to mathematical function>
#> 

This returns a list, with a result and an error element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM