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

kra*_*r65 9 python exception try-catch

我正在使用一个 python 库,其中有一次异常定义如下:

raise Exception("Key empty")
Run Code Online (Sandbox Code Playgroud)

我现在希望能够捕捉到那个特定的异常,但我不知道该怎么做。

我尝试了以下

try:
    raise Exception('Key empty')
except Exception('Key empty'):
    print 'caught the specific exception'
except Exception:
    print 'caught the general exception'
Run Code Online (Sandbox Code Playgroud)

但这只是打印出来caught the general exception

有谁知道我如何捕捉那个特定的Key empty异常?欢迎所有提示!

Vik*_*ngh 6

定义您的例外:

class KeyEmptyException(Exception):
    def __init__(self, message='Key Empty'):
        # Call the base class constructor with the parameters it needs
        super(KeyEmptyException, self).__init__(message)
Run Code Online (Sandbox Code Playgroud)

用它:

try:
    raise KeyEmptyException()
except KeyEmptyException as e:
    print e
Run Code Online (Sandbox Code Playgroud)

更新:基于 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)
Run Code Online (Sandbox Code Playgroud)