[R] Checking for a proper "stop" statement...
Duncan Murdoch
murdoch.duncan at gmail.com
Wed Feb 21 22:51:49 CET 2018
On 21/02/2018 4:28 PM, Jonathan Greenberg wrote:
> Folks:
>
> Consider the following two use cases:
>
> goodfunction <- function()
> {
> stop("Something went wrong..."
> }
>
> # vs.
>
> badfunction <- function()
> {
> notgood()
> }
>
> Is there a way for me to test if the functions make use of a stop()
> statement WITHOUT modifying the stop() output (assume I can't mod the
> function containing the stop() statement itself)? For "goodfunction" the
> answer is TRUE, for "badfunction" the answer is FALSE. Both return an
> error, but only one does it "safely".
>
> I thought the answer might lie in a tryCatch statement but I'm having a
> hard time figuring out how to do this test.
>
I think tryCatch() is what you want. To see the difference between
those two errors, run
tryCatch(goodfunction(), error = function(e) browser())
and similarly with badfunction(). When you land in the browser, you'll see
Browse[1]> str(e)
List of 2
$ message: chr "Something went wrong..."
$ call : language goodfunction()
- attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
and
Browse[1]> str(e)
List of 2
$ message: chr "could not find function \"notgood\""
$ call : language notgood()
- attr(*, "class")= chr [1:3] "simpleError" "error" "condition"
so you could write a test based on the message, or based on the call to
see where the stop() happened.
Duncan Murdoch
More information about the R-help
mailing list