我正在使用一个 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'
但这只是打印出捕获了一般异常
。
有谁知道我如何捕获特定的 Key empty
异常?欢迎所有提示!
定义你的异常:
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 中的讨论:
But the lib is not under my control. It's open source, so I can edit it, but I would preferably try to catch it without editing the library. Is that not possible?
假设库抛出异常
# 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)