Equivalent of "Throw" in R

Equivalent of throw in R

See help(tryCatch):

Conditions are signaled by
'signalCondition'. In addition, the

'stop' and 'warning' functions have
been modified to also accept

condition arguments.

and later under 'See Also':

'stop' and 'warning' signal conditions, and 'try' is essentially a
simplified version of 'tryCatch'.

so you probably want stop.

How to return a error message in R?

Since you don't specify what you really want, all I just can say is take a look at

?message # prints a message but not stop execution
?warning # prints a warning message but not stop execution
?stop # stops execution of the current expression and executes an error action.

Exception handling in R

Besides Shane's answer pointing you to other StackOverflow discussions, you could try a code search feature. This original answer pointed to Google's Code Search has since been discontinued, but you can try

  • Github search as e.g. in this query for tryCatch in language=R;
  • Ohloh/Blackduck Code search eg this query for tryCatch in R files
  • the Debian code search engine on top of the whole Debian archive

Just for the record, there is also try but tryCatch may be preferable. I tried a quick count at Google Code Search but try gets too many false positives for the verb itself -- yet it seems tryCatch is more widely used.

How to write trycatch in R

Well then: welcome to the R world ;-)

Here you go

Setting up the code

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 inside 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)
}

Applying the code

> y <- lapply(urls, readUrl)
Processed URL: http://stat.ethz.ch/R-manual/R-devel/library/base/html/connections.html
Some other message at the end
Processed URL: http://en.wikipedia.org/wiki/Xz
Some other message at the end
URL does not seem to exist: xxxxx
Here's the original error message:
cannot open the connection
Processed URL: xxxxx
Some other message at the end
Warning message:
In file(con, "r") : cannot open file 'xxxxx': No such file or directory

Investigating the output

> head(y[[1]])
[1] "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"
[2] "<html><head><title>R: Functions to Manipulate Connections</title>"
[3] "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"
[4] "<link rel=\"stylesheet\" type=\"text/css\" href=\"R.css\">"
[5] "</head><body>"
[6] ""

> length(y)
[1] 3

> y[[3]]
[1] NA

Additional remarks

tryCatch

tryCatch returns the value associated to executing expr unless there's an error or a warning. In this case, specific return values (see return(NA) above) can be specified by supplying a respective handler function (see arguments error and warning in ?tryCatch). These can be functions that already exist, but you can also define them within tryCatch() (as I did above).

The implications of choosing specific return values of the handler functions

As we've specified that NA should be returned in case of error, the third element in y is NA. If we'd have chosen NULL to be the return value, the length of y would just have been 2 instead of 3 as lapply() will simply "ignore" return values that are NULL. Also note that if you don't specify an explicit return value via return(), the handler functions will return NULL (i.e. in case of an error or a warning condition).

"Undesired" warning message

As warn=FALSE doesn't seem to have any effect, an alternative way to suppress the warning (which in this case isn't really of interest) is to use

suppressWarnings(readLines(con=url))

instead of

readLines(con=url, warn=FALSE)

Multiple expressions

Note that you can also place multiple expressions in the "actual expressions part" (argument expr of tryCatch()) if you wrap them in curly brackets (just like I illustrated in the finally part).

Why doesn't R throw an error when I use only the initial part of my column name in a data frame?

Probably worthwhile to augment all comments into an answer.


Both my comment and BenBolker's point to doc page ?Extract:

Under Recursive (list-like) objects:

Both "[[" and "$" select a single element of the list. The main difference is that "$" does not allow computed indices, whereas "[[" does. x$name is equivalent to x[["name", exact = FALSE]]. Also, the partial matching behavior of "[[" can be controlled using the exact argument.

Under Character indices:

Character indices can in some circumstances be partially matched (see ?pmatch) to the names or dimnames of the object being subsetted (but never for subassignment). Unlike S (Becker et al p. 358), R never uses partial matching when extracting by "[", and partial matching is not by default used by "[[" (see argument exact).

Thus the default behaviour is to use partial matching only when extracting from recursive objects (except environments) by "$". Even in that case, warnings can be switched on by options(warnPartialMatchDollar = TRUE).

Note, the manual has rich information, and make sure you fully digest them. I formatted the content, adding Stack Overflow threads behind where relevant.


Links provided by phiver's comment are worth reading in a long term.

Returning an error message other than the last one thrown in R

@aurèle answered this in the comments.

This happens because of the lazy evaluation of function parameters. force(num) will change the behavior and evaluate the first constructor.

RxJS throw new Error vs Observable.throw

Observable.throw returns an error when in streams. For example I am expecting an Observable but for some reason, I want to return an error. These cases its not possible to use throw new Error() .

For example:

var source = someStream$
.flatMap(data => data?
Rx.Observable.of(data): // Or any other async operation
Rx.Observable.throw('invalid data'));

Here flatMap expects an Observable stream, if we need to use throw new Error() we need to do a hack .

It might have other advantages also to work well with the rx operators,that I am not aware of .

Calling stop( ) within function causes R CMD Check to throw error

Since your function has global side effects, I think check isn't going to like it. It would be different if you required the user to put tryCatch at the top level, and then let it catch the error. But think about this scenario: a user defines f() and calls it:

f <- function() {
call_your_function()
do_something_essential()
}
f()

If your function silently caused it to skip the second line of f(), it could cause a lot of trouble for the user.

What you could do is tell the user to wrap the call to your function in tryCatch(), and have it catch the error:

f <- function() {
tryCatch(call_your_function(), error = function(e) ...)
do_something_essential()
}
f()

This way the user will know that your function failed, and can decide whether or not to continue.

From discussion in the comments and your edit to the question, it seems like your function is only intended to be used interactively, so the above scenario isn't an issue. In that case, you can avoid the R CMD check problems by skipping the example unless it is being run interactively. This is fairly easy: in the help page for a function like create_directories(), set up your example as

if (interactive()) {
create_directories()
# other stuff if you want
}

The checks are run with interactive() returning FALSE, so this will stop the error from ever happening in the check. You could also use tryCatch within create_directories() to catch the error coming up from below if that makes more sense in your package.



Related Topics



Leave a reply



Submit