[Python-ideas] Let try-except check the exception instance

Antoine Pitrou solipsis at pitrou.net
Fri Jun 1 04:10:34 EDT 2018

On Thu, 31 May 2018 14:00:24 -0400
Alexander Belopolsky
<alexander.belopolsky at gmail.com> wrote:
> Is this really true?  Consider the following simple code
> class E(Exception):
>     def __init__(self):
>         print("instantiated")
> try:
>     raise E
> except E:
>     pass
> Is it truly necessary to instantiate E() in this case?  Yet when I run it,
> I see "instantiated" printed on the console.

I don't think it's truly necessary, but there's enough complication
nowadays in the exception subsystem (e.g. with causes and contexts)
that at some point we (perhaps I) decided it made things less hairy to
always instantiate it in an "except" clause.

Let me stress, though: this happens when catching exceptions in
*Python*.  When in C you call PyErr_ExceptionMatches, the exception
should not get instantiated.



More information about the Python-ideas mailing list