Raise X or Raise X()?

Chris Rebert clp2 at rebertia.com
Sun Mar 11 17:49:25 EDT 2012


On Sun, Mar 11, 2012 at 1:37 PM, Irmen de Jong <irmen.NOSPAM at xs4all.nl> wrote:
> On 11-3-2012 20:04, bvdp wrote:
>> Which is preferred in a raise: X or X()? I've seen both. In my specific case I'm dumping out of a deep loop:
>>
>> try:
>>   for ...
>>     for ...
>>       for ...
>>         if match:
>>            raise StopInteration()
>>          else ...
>>
>> except StopInteration:
>>    print "found it"
>
> "raise X" is a special case of the 3-args raise. Effectively it just raises an instance
> of X which is constructed with an empty argument list. Therefore, "raise X()" is
> equivalent, as far as I know.
>
> See http://docs.python.org/reference/simple_stmts.html#the-raise-statement

Note that the 3-argument form of `raise` has been eliminated in Python 3.
However, both:
    raise an_exception_instance
and:
    raise AnExceptionClass # will have a blank error message
are still permitted.

Interesting stylistic question though. I'd support the X() form for
uniformity with the majority of cases where an error message is
specified for the exception.

Cheers,
Chris



More information about the Python-list mailing list