在 Python 中向异常添加数据

Ray*_*emi 2 python exception

我正在尝试创建一个包含典型字符串和附加数据的异常:

class MyException(RuntimeError):
    def __init__(self,numb):
        self.numb = numb

try:
    raise MyException("My bad", 3)
except MyException as me:
    print(me)
Run Code Online (Sandbox Code Playgroud)

当我运行上面的代码时,我得到了一个明显的抱怨,即我只有两个参数,__init__但我通过了三个参数。我不知道如何将典型字符串放入我的异常中并添加数据。

Ray*_*emi 8

基于上面答案的更新代码如下所示:

class MyException(RuntimeError):
    def __init__(self,message,numb):
        super().__init__(message)
        self.numb = numb

try:
    raise MyException("My bad", 3)
except MyException as me:
    print(me)
    print(me.numb)
Run Code Online (Sandbox Code Playgroud)

它输出

    My bad
    3
Run Code Online (Sandbox Code Playgroud)


Ada*_*hes 5

您可以将第一个 arg ( arg1)传递给父异常的构造函数,然后使用第二个参数执行您想要的操作。

class MyException(RuntimeError):
    def __init__(self, arg1, arg2):
        super().__init__(arg1)
        print("Second argument is " + arg2)
Run Code Online (Sandbox Code Playgroud)

注意 - 如果使用 Python 2,则调用super()替换为super(MyException, self)