python 不能在处理程序中使用异常字段

python cannot use exception fields in handler

我正在为 class 作业构建一个汇编程序。我的程序所做的是读取文件而不是吐出机器代码,(在剥离注释等之后......但一切正常)。

我要做的是在所有这些之上构建一个异常处理程序,以便它可以捕获错误代码抛出的异常,我可以通过打印出错误代码所在的行来处理它们,这样就很容易了调试错误代码。

我的问题是我不知道如何访问被捕获的异常实例。我找到的所有内容似乎都为我提供了异常的 class 对象。

现在我收到这样的错误:

AttributeError: 'UnknownCommandException' object has no attribute 'line'

这是我现在处理异常的顶级程序:

import tkinter as tk
from tkinter.filedialog import *
from assembler import readCodeFromFile
from exceptions import UndeclaredLabelException
from exceptions import UnknownCommandException
from exceptions import RegisterNotFoundException

def main():
    readFileStr = tk.filedialog.askopenfilename()
    wrtFile = readFileStr.replace(".txt","") + "ASSEMBLY.txt"
    try:
        readCodeFromFile(readFileStr, wrtFile, base="*")
    except UndeclaredLabelException as e:
        print("undeclared label '{}' near line {}".format(e.label, e.line)) 
        print(e)
    except UnknownCommandException as e:
        print("unknown command '{}' near line {}".format(e.inst, e.line))
        print(e)
    except RegisterNotFoundException as e:
        print("unknown reg '{}' near line {}".format(e.reg, e.line))
        print(e)
if __name__ == "__main__":
    main()

我也绑定使用 sys.exc_info() 这对我也不起作用。

定义异常的代码。

class RegisterNotFoundException(Exception):
    """this exception is thrown when a string does not match any of the known registers for this language."""
    def __init__ (self, reg, line):
        self.reg = reg
        self.line = line   
class UnknownCommandException(Exception):
    """this exception is thrown when a nonexistant command is used."""
    def __init__(self, inst, line):
        self.inst = inst
        self.lineNumber = line
class UndeclaredLabelException(Exception):
    """this exception is thrown when a label is used but has not been declared."""
    def __init__(self, label, line):
        self.badLabel = label
        self.lineNumber = line
    def __repr__ (self):
        return "bad label: '" + self.badLabel + "'"

我发现这段代码可以很好地处理我的 RegisterNotFoundException,但不能很好地处理其他两个,这让我比以前更加困惑。

UnknownCommandExceptionUndeclaredLableException class 初始值设定项中,代码将 line 参数分配给名为 lineNumber 的属性。如果您不能(或不想)更改异常,则需要在异常处理代码中查找该属性:

except UndeclaredLabelException as e:
    print("undeclared label '{}' near line {}".format(e.label, e.lineNumber)) 
    print(e)
except UnknownCommandException as e:
    print("unknown command '{}' near line {}".format(e.inst, e.lineNumber))
    print(e)

RegisterNotFoundException 确实使用 line 作为属性名称,因此您现有的代码应该已经适用于那些。

您使用的属性名称不一致。您正在很好地处理异常,只是混淆了名称。

您的两个异常使用 lineNumber 作为属性:

class UnknownCommandException(Exception):
    """this exception is thrown when a nonexistant command is used."""
    def __init__(self, inst, line):
        self.inst = inst
        self.lineNumber = line
        #    ^^^^^^^^^^

class UndeclaredLabelException(Exception):
    """this exception is thrown when a label is used but has not been declared."""
    def __init__(self, label, line):
        self.badLabel = label
        self.lineNumber = line
        #    ^^^^^^^^^^

但是您的异常处理程序正在尝试访问 line 属性:

except UndeclaredLabelException as e:
    print("undeclared label '{}' near line {}".format(e.label, e.line)) 
    #                                                            ^^^^
    print(e)
except UnknownCommandException as e:
    print("unknown command '{}' near line {}".format(e.inst, e.line))
    #                                                          ^^^^
    print(e)

另请注意 UndeclaredLabelException.badLabele.label 属性。

要么重命名 class 上的属性,要么在异常处理程序中访问正确的属性。