简体   繁体   中英

Python catch exception

I am having difficulty working with the two exceptions raised by lookup(self, key) . Both are ValueError exceptions, yet mean entirely different things. 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? 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. It's hackish and fragile, but you can tell the difference by peeking at the message attribute on the exception object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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