我正在使用一个 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
例外?欢迎所有提示!
定义您的例外:
class KeyEmptyException(Exception):
def __init__(self, message='Key Empty'):
# Call the base class constructor with the parameters it needs
super(KeyEmptyException, self).__init__(message)
Use it:
try:
raise KeyEmptyException()
except KeyEmptyException as e:
print e
更新:基于评论OP中的讨论:
但该库不在我的控制之下。它是开源的,所以我可以编辑它,但我最好尝试在不编辑库的情况下捕获它。那不可能吗?
说图书馆引发异常
# 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)