kjo
kjo

Reputation: 35301

How to target exception-handling to specific exceptions?

Does R provide any support for targetting exception handling to only specific exceptions?


In Python, for example, one can narrow down exception-handling to specific exception types; e.g.:

try:
    return frobozz[i]
except IndexError:
    return DEFAULT

In this example, the exception handling will kick in only if i is an integer such that i >= len(frobozz) or i < -len(frobozz), but will not catch the exception resulting from, e.g., the case where i is the string "0" (which would be a TypeError, rather than an IndexError).

Upvotes: 1

Views: 320

Answers (1)

JWLM
JWLM

Reputation: 442

Wellllll...yes and no, and mostly no.

Every Python exception is wrapped in a particular error class which derives from Error, and Python modules are supposed to raise the "right" kinds of errors. For instance, an index out of range error should throw IndexError. The base language knows about these errors and so you can catch the appropriate error type in your except... clause.

R doesn't do that. Errors are untyped; there's no essential difference between an index out of bounds error and any other error.

That said, you can cheat under certain, very limited, circumstances.

> y <- tryCatch(x[[2]], error = function(e) e)
> y
<simpleError in x[[2]]: subscript out of bounds>
> y$message
[1] "subscript out of bounds"

The key here is the use of the tryCatch function and the error clause. The error clause in a tryCatch is a function of one variable which can perform arbitrary operations on e, which is an object of type 'simpleError' and contains an item named "message". You can parse message and handle interesting cases separately

> y <- tryCatch(x[[2]], 
  error = function(e) {
    if ('subscript out of bounds' == e$message) return(NA) else stop(e))
  })
 > y
 [1] NA

This only works if you can actually detect the error string you want to look for, and that isn't guaranteed. (Then again, it also isn't guaranteed in Python, so things aren't really much different from one another.)

Final question, though: why in Heaven's name are you doing this? What are you really trying to do?

Upvotes: 1

Related Questions