python - 为什么我的用户定义的异常没有得到正确处理?

标签 python

我想知道我在我的 python 程序中从一个类中引发的用户定义的异常没有被我的 main() 中正确的异常处理程序处理。假设我有一个类:

class Pdbalog:
    # Constructor
    def __init__(self, logtype):
        if logtype == 1 or logtype == 2:
            # These are valid
            self.logtypeV = logtype
            ...<continue processing>
        else:
            # Invalid
            raise Exception("Invalid Logtype")

我的 main 看起来像:

from pdbalog import *
def main():
    try:
        mylog = Pdbalog(10)
        ...<other code here>

    except "Invalid Logtype":
        print('Exiting...')
    except:
        print('Unhandled exception')
        raise

我希望当 main 运行时,我实例化 Pdbalog 对象的行会引发异常 (Exception("Invalid Logtype")) 和 main 中的异常处理程序(except "Invalid Logtype")将打印输出字符串 "Exiting..."。然而,事实并非如此。它由未处理的异常处理程序处理。最终发生的是正在输出字符串 "Unhandled exception"。为什么不是

    except "Invalid Logtype":

处理异常?

我使用的是旧版本的 python (2.4)。

最佳答案

Exception("Invalid Logtype") 仍然只是一个Exception,只是现在有一条错误消息。 "Invalid Logtype" 不是错误,只是一个 str,因此您无法捕获它。

尝试:

class InvalidLogtype(Exception): pass

try:
    raise InvalidLogType
except InvalidLogType:
    pass

请注意,您可以根据错误消息进行捕获

except Exception, e:
    if e.args == ("Invalid Logtype",):
        ...

    else:
        raise

关于python - 为什么我的用户定义的异常没有得到正确处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19035244/

相关文章:

Python正则表达式,匹配多个整数

python - Django 测试 - 在所有测试中修补对象

python - Tensorflow:InvalidArgumentError:您必须使用 dtype int32 为占位符张量 'yy' 提供一个值

python - Yum 不在 CentOS 7 上安装某些软件包

python - 如何让 Cherry Py 将浏览器重定向到网站?

python - 为什么operator模块没有逻辑或功能?

python - Pandas 轴解释

python - 处理列表给出错误 "list indices must be integers or slices, not tuple"

Python if/else 语句混淆

Python:覆盖 __new__ 中的 __init__ args