python中能主动引发异常的是_在python中引发异常的正确方法?

Here is the simple code:

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'

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

See the documentation for the raise statement

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:

When raising an exception, use raise ValueError('message') instead of the older form raise ValueError, 'message'.

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 will no longer support that form.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值