Domanda

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

È stato utile?

Soluzione

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

Altri suggerimenti

You can use whichever form you like. There is no real difference and both are legal in Python 2 and 3. Python style guide does not specify which one is recommended.


A little more information on the "class form" support:

try:
    raise KeyboardInterrupt

This form is perfectly legal in both Python 2 and 3. Excerpt from pep-3109:

raise EXCEPTION is used to raise a new exception. This form has two sub-variants: EXCEPTION may be an exception class or an instance of an exception class; valid exception classes are BaseException and its subclasses [5]. If EXCEPTION is a subclass, it will be called with no arguments to obtain an exception instance.

It is also described in Python documentation:

... If it is a class, the exception instance will be obtained when needed by instantiating the class with no arguments.

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top