开发者

Python, rasing an exception without arguments

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

try:
    r开发者_如何学编程aise 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


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜