我正在使用一个python库,其中一个异常定义如下:
raise Exception("Key empty")
我现在希望能够捕获该特定异常,但我不知道该怎么做。
我尝试了以下
try:
raise Exception('Key empty')
except Exception('Key empty'):
print 'caught the specific exception'
except Exception:
print 'caught the general exception'
但是只打印出caught the general exception
。
有人知道如何捕获特定的Key empty
例外情况吗?欢迎所有提示!
答案 0 :(得分:2)
定义您的例外:
class KeyEmptyException(Exception):
def __init__(self, message='Key Empty'):
# Call the base class constructor with the parameters it needs
super(KeyEmptyException, self).__init__(message)
使用它:
try:
raise KeyEmptyException()
except KeyEmptyException as e:
print e
更新:根据评论OP中的讨论发布:
但是lib不在我的控制之下。它是开源的,所以我可以编辑它,但我最好尝试在不编辑库的情况下捕获它。这不可能吗?
说库引发了一个例外
# this try is just for demonstration
try:
try:
# call your library code that can raise `Key empty` Exception
raise Exception('Key empty')
except Exception as e:
# if exception occurs, we will check if its
# `Key empty` and raise our own exception
if str(e) == 'Key empty':
raise KeyEmptyException()
else:
# else raise the same exception
raise e
except Exception as e:
# we will finally check what exception we are getting
print('Caught Exception', e)
答案 1 :(得分:1)
你需要继承Exception
:
class EmptyKeyError(Exception):
pass
try:
raise EmptyKeyError('Key empty')
except EmptyKeyError as exc:
print(exc)
except Exception:
print('caught the general exception')