Checking for an exception

Steve D'Aprano steve+python at pearwood.info
Sat Jun 24 21:15:01 EDT 2017


On Sun, 25 Jun 2017 09:37 am, Cameron Simpson wrote:

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

Both Python 2 and Python 3 support raising either exception classes or exception
instances:

raise ValueError
raise ValueError('message')

both work. (If you use a type alone, the raise statement automatically
instantiates it, otherwise it just uses the instance you give.)


> Also, do you need the "isinstance(obj, type)" precursor to the 
> issubclass?

Yes, because annoyingly issubclass raises if you pass something which isn't a
type, instead of just returning False:


py> issubclass(99, int)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: issubclass() arg 1 must be a class



> Might you be better with:
> 
>   return ( issubclass(obj, BaseException)
>            if isinstance(obj, type)
>            else isinstance(obj, BaseException)
>          )
> 
> ?

I didn't think of that. If I were just supporting Python 2.7 or 3.6, I think I
would prefer that, but for my sins I'm supporting 2.4 :-(


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

I have a decorator which converts exceptions in the decorated function from one
type to another. It requires as two arguments:

- the exception to be caught: an exception type, or a tuple of exception types

- the exception to be re-raised: an exception type, or an exception instance


If the caller provides bad arguments to the decorator, I want to raise
*immediately*, not when the decorated function is called.



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