views:

43

answers:

2

Hi, I would like to know the best practice about raising an exception without arguments. In the official python documentation, you can see this :

try:
    raise KeyboardInterrupt

(http://docs.python.org/tutorial/errors.html chap. 8.6)

and in some differents code, like Django or Google code, you can see this :

  def AuthenticateAndRun(self, username, password, args):
    raise NotImplementedError()

(http://code.google.com/p/neatx/source/browse/trunk/neatx/lib/auth.py)

The exception is instanciate before being raised while there is no argument. What is the purpose to instanciate an exception without arguments ? When I should use the first case or the second case ?

Thanks in advance Fabien

+2  A: 

Raising an exception class instead of an exception instance is deprecated syntax and should not be used in new code.

raise Exception, "This is not how to raise an exception..."
Ignacio Vazquez-Abrams
For those curious, see http://www.python.org/dev/peps/pep-0352/#transition-plan for more info about exception-related deprecation.
Wayne Werner
I'm not able to figure out what you're recommending. Your code example seems to be what **not** to do. Perhaps you should show what *should* be done.
S.Lott
A: 

In languages like C++ you can raise any object, not just Exceptions. Python is more constrained. If you try :

raise 1

You get:

Traceback (most recent call last):
...
TypeError: exceptions must be old-style classes or derived from BaseException, not int

In python programming model you can usually use a class by itself instead of an instance (this is handy for fast creation of unique instances, just define a class). Hence no wonder you can raise an exception class instead of an exception instance.

However like Ignacio said, that is deprecated.

Also, some side-note that is not the direct question:

You could also see raise alone by itself in some code. Without any object class or anything. It is used in exception handlers to re-raise the current exception and will keep the initial traceback.

kriss