如何在 Python 中捕获自定义异常 [英] How to catch custom exception in Python
问题描述
我正在使用一个 python 库,其中有一次异常定义如下:
I'm using a python library in which at one point an exception is defined as follows:
raise Exception("Key empty")
我现在希望能够捕获该特定异常,但我不知道该怎么做.
I now want to be able to catch that specific exception, but I'm not sure how to do that.
我尝试了以下
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
异常吗?欢迎所有提示!
Does anybody know how I can catch that specific Key empty
exception? All tips are welcome!
推荐答案
定义您的例外:
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 发布的评论中的讨论:
Update: based on the discussion in comment OP posted:
但是这个库不在我的控制之下.它是开源的,所以我可以编辑它,但我最好尝试在不编辑库的情况下捕获它.这不可能吗?
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)
这篇关于如何在 Python 中捕获自定义异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!