在python中引发异常的正确方法? [英] Proper way to raise exception in python?

查看:106
本文介绍了在python中引发异常的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是简单的代码:

import sys

class EmptyArgs(StandardError):
    pass

if __name__ == "__main__":
    #first way to raise exception
    if len(sys.argv) == 1:
       raise EmptyArgs     
    #second way to raise exception
    if len(sys.argv) == 1:
       raise EmptyArgs()

更多正确的方式是?

注意:在我的真实代码中,异常与我声明的完全相同:没有消息和参数。

Which way is "more" correct? Both are working.
Note: In my real code, exception is exactly the same as I declared: without message and arguments.

推荐答案

两者都是正确的;后一种形式让您为异常附加参数:

Both are proper; the latter form let's you attach arguments to your exception:

if len(sys.argv) == 1:
   raise EmptyArgs('Specify at least 1 argument')

您也可以将参数作为第二个参数传递值作为加元语句中的元组:

You can also pass in the arguments as a second value as a tuple in the raise statement:

if len(sys.argv) == 1:
   raise EmptyArgs, ('Specify at least 1 argument',)

,但单个非元组值也将起作用,并且被视为单个参数:

but a single non-tuple value will work too, and is regarded as a single argument:

if len(sys.argv) == 1:
   raise EmptyArgs, 'Specify at least 1 argument'

,第三个值为 raise 让我们指定一个替代回溯,然后使用它代替代码中当前位置生成的回溯:

and a third value to raise let's you specify an alternate traceback, which then is used instead of a traceback that would be generated for the current location in the code:

if len(sys.argv) == 1:
   raise EmptyArgs, ('Specify at least 1 argument',), traceback_object

S ee raise 语句

See the documentation for the raise statement

请注意,当您对异常使用参数时, Python样式指南PEP 8 希望您提供一个异常实例,而不是类:

Note that when you do use arguments for your exception, The Python styleguide PEP 8 prefers you provide an exception instance, and not a class:


引发异常时,请使用 raise ValueError('message')代替较旧的格式 raise ValueError,'message'

首选使用括号形式,因为当异常参数很长或包含字符串格式时,您无需使用行连续字符,多亏了括号。旧版本的表单将在Python 3中删除。

The paren-using form is preferred because when the exception arguments are long or include string formatting, you don't need to use line continuation characters thanks to the containing parentheses. The older form will be removed in Python 3.

Python 3将不再支持该表单。

Python 3 will no longer support that form.

这篇关于在python中引发异常的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆