Checking for an exception

Steve D'Aprano steve+python at pearwood.info
Sat Jun 24 07:48:37 EDT 2017


On Sat, 24 Jun 2017 09:23 pm, mbyrnepr2 at gmail.com wrote:

> On Saturday, June 24, 2017 at 11:31:11 AM UTC+1, Steve D'Aprano wrote:
>> 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.)
>> 
>> I have:
>> 
>> return (isinstance(obj, type) and issubclass(obj, BaseException)
>>         or isinstance(obj, BaseException))
>> 
>> 
>> Any better ideas?


> Would something along these lines help?
> 
> import exceptions

py> import exceptions
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'exceptions'


What module are you importing?



> if 'ArithmeticError' in dir(exceptions):
>     print 'is an exception'


I don't understand that. I'm not looking for strings which happen to match the
names of built-in exceptions, I'm looking to test for any object which is an
exception. To be an exception, you must inherit from BaseException.

(String exceptions did work until Python 2.5, but I don't care about them.)



> try:
>     if exceptions.__getattribute__('ArithmeticError'):

You shouldn't call __getattribute__ directly -- that's reserved for Python's
use. You should call getattr() with an optional default value:

if getattr(exceptions, 'ArithmeticError', False):
    print 'is an exception'
else:
    print 'is an exception'


But in any case, no, I don't want to look up a string in some list of
exceptions. That won't test for exceptions that aren't in the list.

class MyCustomException(LookupError):
    pass




-- 
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