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

时间:2015-02-25 08:04:05

标签: python exception-handling

我为类分配构建汇编程序。我的程序所做的是读取文件而不是吐出机器代码,(在删除注释等之后......但这一切都有效)。

我要做的就是在所有这些之上构建一个异常处理程序,以便它能够捕获坏代码引发的异常,并且我可以通过打印出坏代码所在的行来处理它们#&# 39;很容易调试坏代码。

我的问题是我无法弄清楚如何访问被捕获的异常实例。我找到的所有内容似乎特别为我提供了异常的类对象。

现在我收到这样的错误:

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很好,但不是其他两个,这让我比以前更加困惑。

2 个答案:

答案 0 :(得分:1)

您使用的是不一致的属性名称。你正在处理你的例外情况,你只需要混淆名称。

您的两个例外使用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属性。

重命名该类的属性,或访问异常处理程序中的正确属性。

答案 1 :(得分:0)

UnknownCommandExceptionUndeclaredLableException类初始值设定项中,代码将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作为属性名称,因此您现有的代码应该适用于已有的代码。