我正在为一个类作业构建一个汇编程序。我的程序所做的是读取文件而不是吐出机器代码(在条带化注释等之后)。。。但这一切都是可行的)。你知道吗
我要做的是在所有这些之上构建一个异常处理程序,这样它就可以捕获坏代码抛出的异常,并且我可以通过打印出坏代码所在的行来处理它们,这样就很容易调试坏代码。你知道吗
我的问题是我不知道如何访问捕获的异常实例。我找到的所有东西似乎都给了我异常的类对象。你知道吗
现在我遇到了这样的错误:
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
,但不能处理其他两个,这让我比以前更加困惑。你知道吗
在
UnknownCommandException
和UndeclaredLableException
类初始值设定项中,代码将line
参数指定给名为lineNumber
的属性。如果不能(或不想)更改异常,则需要在异常处理代码中查找该属性:RegisterNotFoundException
确实使用了line
作为属性名,因此您的现有代码应该已经可以处理这些属性了。你知道吗您使用的属性名称不一致。你处理异常很好,只是把名字弄混了。你知道吗
两个异常使用
lineNumber
作为属性:但是异常处理程序正在尝试访问
line
属性:还要注意
UndeclaredLabelException.badLabel
和e.label
属性。你知道吗重命名类上的属性,或者访问异常处理程序中的正确属性。你知道吗
相关问题 更多 >
编程相关推荐