对try/except与自定义异常混淆

2024-06-08 06:16:09 发布

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

我的代码:

class AError(Exception):
    print 'error occur'
for i in range(3):
    try:
        print '---oo'
        raise AError
    except AError:
        print 'get AError'
    else:
        print 'going on'
    finally:
        print 'finally'

当我运行上述代码时,输出如下:

^{pr2}$

我认为字符串"error occur"应该出现三次,就像"---oo",但它只出现一次;为什么?在


Tags: 代码inforexceptionrangeerrorclassoo
3条回答

我强烈建议不要在你的异常中放置任何print语句,尤其是它们的构造函数!例外是语义实体,如果需要,可以打印出来。如果必须自动打印,请至少使用logging或类似的软件包。在

您可能不知道的是,您可以收集异常实例以在except子句中使用,如下所示:

class MyError(Exception):
    pass

for i in range(3):
    try:
        print '---oo'
        raise MyError("error msg no. {}".format(i))
        # Exception usually always accept a string as their first parameter
    except MyError, ex:
        # Exception instance available inside the except clause as `ex`
        print ex
    else:
        print 'going on'
    finally:
        print 'finally'

为了澄清Paul's answer,下面是一个简单的例子:

class Test(object):

    print "Class being defined"

    def __init__(self):
        print "Instance being created"


for _ in range(3):
    t = Test()

由此产生的输出将是:

^{pr2}$

class定义内但在方法def初始化之外的代码在定义类时只运行一次。在

如果您希望代码在创建实例时运行,那么它应该在__init__实例方法中(或者,偶尔使用__new__类方法)。但是,请注意,如果您为子类定义__init__,您可能应该确保它也调用了超类的__init__

class AError(Exception):

    def __init__(self, *args, **kwargs):
        Exception.__init__(self, *args, **kwargs) # call the superclass
        print 'error occur' # print your message

这确保了子类支持超类的参数;在Exception的情况下,可以传递错误消息:

>>> raise AError("Something went wrong.")
error occur # your message gets printed when the instance is created

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    raise AError("Something went wrong.")
AError: Something went wrong. # the error message passes through to the traceback

有关*args, **kwargs语法的解释,如果您不熟悉,请参见例如What does ** (double star) and * (star) do for parameters?。{3}你也可以使用超类来调用。在

对于整个类,'error occur'只打印一次。在

您可能期望它为所创建的类的每个实例运行。在

为了实现这一点,请将其放入__init__函数中

class AError(Exception):
    def __init__(self):
        print 'error occur'

在创建AError的实例时调用__init__。在

相关问题 更多 >

    热门问题