Checking for an exception

Cameron Simpson cs at zip.com.au
Sat Jun 24 19:37:30 EDT 2017


On 24Jun2017 20:31, Steve D'Aprano <steve+python at pearwood.info> 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))

I haven't a better idea.

Are you supporting Python 2 here, where one can raise bare exceptions instead 
of instances? Also, do you need the "isinstance(obj, type)" precursor to the 
issubclass?

Might you be better with:

  return ( issubclass(obj, BaseException)
           if isinstance(obj, type)
           else isinstance(obj, BaseException)
         )

?

Curious: why do you need to test this? Some function which may return a "value" 
or an exception?

Cheers,
Cameron Simpson <cs at zip.com.au>



More information about the Python-list mailing list