Checking for an exception

Ben Finney ben+python at benfinney.id.au
Sat Jun 24 20:49:20 EDT 2017


Steve D'Aprano <steve+python at pearwood.info> writes:

> What's the right/best way to test whether an object is an exception
> ahead of time? (That is, without trying to raise from it.)

This being Python, it is Easier to Ask for Forgiveness than for
Permission.

The corollary of that is, if you try to ask permission first (to Look
Before You Leap), it will likely not be as easy as simply using the
object as you intend to use it.

So, EAFP would suggest just raising the object:

    raise obj

and thereby reveal the bug in the *caller's* code if it tries to pass a
not-exception object for that purpose.

> return (isinstance(obj, type) and issubclass(obj, BaseException)
>         or isinstance(obj, BaseException))
>
> Any better ideas?

It's clumsy and noisy, but I think that's the cost of trying to Look
Before You Leap in code.

-- 
 \         “My girlfriend has a queen sized bed; I have a court jester |
  `\   sized bed. It's red and green and has bells on it, and the ends |
_o__)                                         curl up.” —Steven Wright |
Ben Finney




More information about the Python-list mailing list