如何确定KeyError的来源?

时间:2017-07-16 03:36:18

标签: python

我正在使用邻接列表在Python 3.x中编写一个(定向)图的简单实现。要删除图形的边缘,我正在看一个看起来像这样的函数:

class Graph(object):

    def __init__(self):
        self.vertices = {}

    def add_vertex(self, x):
        """ Adds x to the graph, if it doesn't exist """
        if x not in self.vertices:
            self.vertices[x] = set()
        else:
            print("Error: vertex {} already in graph!".format(x))                

    def add_edge(self, x, y):
        """ Adds the edge from x to y, if it doesn't exist """
        try: 
            if y not in self.vertices[x]:
                self.vertices[x].add(y)
            else:
                print("Error: edge already exists!")
        except KeyError:
            print("Error: vertex {} not found!".format(x))

    def remove_edge(self, x, y):
        """ Removes the edge from x to y, if it exists """

        try:
           self.vertices[x].remove(y)
        except KeyError:
           # QUESTION: which part of the try block caused the KeyError?
           print("Error: vertex not found!")

我的问题是因为我正在使用集合字典,两者都可以在

中引发KeyError
self.vertices[x].remove(y)

如果我想打印一条错误消息,指出这两个顶点之一(xy)不存在,是否有办法确定该行的哪一部分引发了错误?或者我是否必须再次检查并将错误消息从(重复)检查中删除?

(注意:我发现上面的代码中存在一些逻辑错误 - 例如,add_edge需要检查x和y是否都存在。)

1 个答案:

答案 0 :(得分:1)

首先,检查图中是否有任何名为x的节点,如果存在,则检查是否存在从x到y的任何边

def remove_edge(self, x, y):
    """ Removes the edge from x to y, if it exists """    
    if x in self.vertices:
        if y in self.vertices[x]:
            self.vertices[x].remove(y)
        else:
            print("There is no edge from x to y")
    else:
         print("There is no node x present in the graph")

如果你真的想知道根据试试赶上

def remove_edge(self, x, y):
    """ Removes the edge from x to y, if it exists """

    try:
       self.vertices[x]
    except KeyError:
       print("Error: vertex x not found!")

    try:
       self.vertices[x].remove(y)
    except KeyError:
       print("Error: vertex y not found!")