Raise X or Raise X()?

Robert Kern robert.kern at gmail.com
Mon Mar 12 13:47:27 CET 2012


On 3/12/12 10:37 AM, Jean-Michel Pichavant wrote:
> 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"
>
> I prefer the raise X() version, it fulfils the zen of python :
>
> "Special cases aren't special enough to break the rules.
> There should be one-- and preferably only one --obvious way to do it."
>
> I still wonder why they've added the class raise form, on which purpose.

The class raise form used to be the only way to raise exceptions. To pass an 
argument, there was special syntax:

   raise Exception, "some message"

This syntax has been done away with in Python 3 in favor of regular calling 
conventions. Python 3 still allows bare classes, though. I also prefer to always 
raise instances of exceptions rather than bare exception classes. It simplifies 
the mental model.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list