Checking for an exception
mbyrnepr2 at gmail.com
mbyrnepr2 at gmail.com
Sat Jun 24 07:23:46 EDT 2017
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?
>
>
>
> --
> Steve
> “Cheer up,” they said, “things could be worse.” So I cheered up, and sure
> enough, things got worse.
Would something along these lines help?
import exceptions
if 'ArithmeticError' in dir(exceptions):
print 'is an exception'
try:
if exceptions.__getattribute__('ArithmeticError'):
print 'is an exception'
except AttributeError:
print 'is not an exception'
try:
getattr(exceptions, 'ArithmeticError')
print 'is not an exception'
except AttributeError:
print 'is not an exception'
More information about the Python-list
mailing list