函数返回None而不是引发Exception

时间:2015-07-23 11:30:16

标签: python exception-handling

我有下一个代码,效果很好。

class AggregateException(Exception):
    pass

class Class(object):
    def some_method(self):
        ...
        try:
            if aggregate(count):
                status = Checked
        except AggregateException:
            status = Rejected
        ...

def aggregate(count):
    if <condition>:
        raise AggregateException('Invalid count')

但是当我尝试简化some_method()的逻辑时,我得到了意想不到的结果。您可以在下面看到代码

class Class(object):
    def some_method(self):
        ...
        self.aggregate_count(count)
        ...
    def aggregate_count(count):
        try:
            if aggregate(count):
                status = Checked
        except AggregateException:
            status = Rejected

aggregate_count()发生错误时,some_method()继续运行而不是完成。

1 个答案:

答案 0 :(得分:0)

我不完全确定你想做什么。但据我所知,如果发生异常,您希望保持程序正常运行。这就是你的脚本正在做的事情。 except语句会捕获您的异常并阻止您的程序崩溃(并更改status)。此后执行some_method - 函数的其余部分。如果要在命令行上看到它,只需将其打印在except块中即可。

如果您要将程序崩溃并将异常打印到命令行,请删除tryexcept声明。

希望有所帮助。

相关问题