简体   繁体   English

Python捕获异常

[英]Python catch exception

I am having difficulty working with the two exceptions raised by lookup(self, key) . 我在处理lookup(self, key)引发的两个异常时遇到困难。 Both are ValueError exceptions, yet mean entirely different things. 两者都是ValueError异常,但含义完全不同。 How do I catch these exceptions separately since they are the same type of exception, but require different behavior upon catching them? 由于它们是相同类型的异常,但是在捕获它们时却需要不同的行为,我如何分别捕获它们? Thanks! 谢谢!

@staticmethod
def _lookup_in_child(child, key):
    if child:
        return child.lookup(key)
    else:
        raise ValueError("Key not in tree: " + repr(key)) 

def lookup(self, key):
    if key is None:
        raise ValueError("None cannot be used as a key")
    if self.key is None:
        raise ValueError("Key not in tree: " + repr(key))

    if key < self.key:
        return self._lookup_in_child(self.left, key)
    elif key > self.key:
        return self._lookup_in_child(self.right, key)
    else:
        return self

I'm not really sure what you're trying to accomplish. 我不太确定您要完成什么。 For instance, couldn't you check if the key is None before calling lookup? 例如,您不能在调用查找之前检查键是否为None吗? Assuming you need to catch the exceptions, the below will do so, and you can then add whatever logic you need based on the specific exception case: 假设您需要捕获异常,下面将进行处理,然后您可以根据特定的异常情况添加所需的任何逻辑:

try:
    lookup(key)
except ValueError, e:
    if str(e) == 'None cannot be used as a key':
        print 'None case'
    elif str(e).startswith('Key not in tree:'):
        print 'Nonexistent case'
    else:
        print 'Default case'

The implementers obviously thought that the two error conditions would be handled the same and that there would be no reason to add something to distinguish them. 实施者显然认为这两个错误条件将被相同地处理,并且没有理由添加一些东西来区分它们。 Contrast this with IOError , where a numeric code is included. 将此与IOError (其中包含数字代码)进行对比。 It's hackish and fragile, but you can tell the difference by peeking at the message attribute on the exception object. 它虽然很脆弱而且很脆弱,但是您可以通过查看异常对象上的message属性来区分它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM