python - 如何在 Python 中捕获自定义异常

标签 python exception try-catch

<分区>

我正在使用一个 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)

关于python - 如何在 Python 中捕获自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45735280/

相关文章:

java - 在 webdriver 中使用 log.error 捕获没有此类元素?

python - 如何将 Dask 数据帧作为 dask-ml 模型的输入传递?

Python,迭代列表理解

Python-写入 CSV 文件的问题

python - 设计朴素贝叶斯分类器时出现属性错误

python - Python 异常的最佳实践?

c# - WCF WebHttp 服务中的错误处理,仅带有 WebFaultException xml 格式的异常

c++ - 自定义异常类 - 奇怪的行为

java - 按下按键后没有选定行 (-1) 时捕获 ArrayIndexOutOfBoundsException

.net - 我可以避免在调试器附带调试器的情况下避免缓慢的.net异常吗?