Python,在没有参数的情况下引发异常

2024-05-28 20:09:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道在没有争论的情况下提出例外的最佳做法。 在python官方文档中,可以看到:

try:
    raise keyboardInterrupt

http://docs.python.org/tutorial/errors.html第8.6章)

在一些不同的代码中,比如Django或Google代码,可以看到:

^{pr2}$

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

当没有参数时,异常在被引发之前是实例化的。 无参数实例化异常的目的是什么?我什么时候该用第一个还是第二个?在

提前谢谢 费宾


Tags: 实例代码文档orghttpdocs参数官方
3条回答

引发异常类而不是异常实例是不推荐使用的语法,不应在新代码中使用。在

raise Exception, "This is not how to raise an exception..."

在C++语言中,可以提高任何对象,而不只是异常。Python更受约束。如果您尝试:

raise 1

你会得到:

^{pr2}$

在python编程模型中,通常可以单独使用类而不是实例(这对于快速创建唯一实例非常方便,只需定义一个类)。因此,难怪可以引发异常类而不是异常实例。在

然而,正如伊格纳西奥所说,这是不赞成的。在

另外,一些旁注并不是直接的问题:

在某些代码中也可以单独看到raise。没有任何对象类或任何东西。它在异常处理程序中用于重新引发当前异常并保留初始回溯。在

你可以用你喜欢的任何形式。两者之间没有真正的区别,在python2和python3中都是合法的。Python style guide没有指定推荐哪一个。在


有关“类表单”支持的更多信息:

try:
    raise KeyboardInterrupt

这种形式在python2和python3中都是完全合法的。 摘录自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.

它也在Python documentation中描述:

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

相关问题 更多 >

    热门问题