Robert Edward Arbon
Robert Edward Arbon

Reputation: 61

Combining tryCatch with s3 custom errors

I'm trying to understand the example given in Hadley Wickham's Advanced R chapter 'Exceptions and Debugging'

Here is the example code:

condition <- function(subclass, message, call = sys.call(-1), ...) {
    structure(
        class = c(subclass, "condition"),
        list(message = message, call = call),
        ...)
    }

custom_stop <- function(subclass, message, call = sys.call(-1), ...) {
    c <- condition(c(subclass, "error"), message, call = call, ...)
    stop(c)
    }

my_log <- function(x) {
    if (!is.numeric(x))
        custom_stop("invalid_class", "my_log() needs numeric input")
    if (any(x < 0))
        custom_stop("invalid_value", "my_log() needs positive inputs")
    log(x)
}

tryCatch(
    my_log("a"),
    invalid_class = function(c) "class",
    invalid_value = function(c) "value" 
)

Wickham says "You can then use tryCatch() to take different actions for different types of errors."

But what is the point of the tryCatch statement here?

If I want the the my_log function to turn a negative value positive then return the log, I can just put the relevant code under the custom_stop("invalid_value"...) line.

My goal is just to be able to write functions which handle errors in a uniform and informative way.

Thanks for your time.

Rob

Upvotes: 2

Views: 159

Answers (1)

BrodieG
BrodieG

Reputation: 52677

The key advantage of emitting custom conditions is that you let someone who doesn't want to modify the functions know how your function failed. For example, suppose that you wanted your users to be able to react differently to different types of failure. If you just used stop they would have no easy way to programmatically determine the nature of the failure.

For example, I can write code like:

x <- "1.1"
tryCatch(
  my_log(x),
  invalid_class=function(c) my_log(as.numeric(x)),
  invalid_value=function(c) my_log(abs(x))
)

Note the above is illustrative and isn't meant to be fully robust, and really, you would probably want to log any conditions that occur and not automatically try to circumvent the problems, but hopefully this illustrates how custom conditions can be useful to your users.

Upvotes: 0

Related Questions