Checking for an exception
Steve D'Aprano
steve+python at pearwood.info
Sat Jun 24 21:31:27 EDT 2017
On Sun, 25 Jun 2017 10:49 am, Ben Finney wrote:
> 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.
Sometimes...
> 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
Unfortunately it's not that simple, as the result of passing a non-exception to
raise is to raise an exception, so I cannot trivially distinguish
between "caller passes an exception" and "caller passes a non-exception"
(result is still an exception).
I could write something like:
def is_exception(obj):
try:
raise obj # This unconditionally raises.
except TypeError:
# Either obj is an instance or subclass of TypeError,
# or it's some arbitrary non-exception object.
if isinstance(obj, TypeError):
return True
try:
return issubclass(obj, TypeError)
except TypeError:
return False
except:
# Any exception other than TypeError means obj is that exception.
return True
else:
# In Python 2.4 and 2.5 you can (but shouldn't) raise strings.
assert isinstance(obj, str)
return False
but I don't think that's much of an improvement :-)
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list