【问题标题】:How to catch custom exception in Python [duplicate]如何在 Python 中捕获自定义异常 [重复]
【发布时间】:2018-01-25 21:05:36
【问题描述】:

我正在使用一个 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 异常吗?欢迎所有提示!

【问题讨论】:

    标签: python exception try-catch


    【解决方案1】:

    定义你的例外:

    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 中的讨论:

    但是这个库不在我的控制之下。它是开源的,所以我可以编辑它,但我最好尝试在不编辑库的情况下捕获它。这不可能吗?

    说库引发异常

    # 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)
    

    【讨论】:

    • 但是这个库不在我的控制之下。它是开源的,所以我可以编辑它,但我最好尝试在不编辑库的情况下捕获它。这不可能吗?
    • 我什至会选择 RuntimeError 作为基类。
    • 如果库引发的异常已修复。然后你必须捕捉到那个异常。您可以捕获该异常并引发您自己的异常作为回报。
    【解决方案2】:

    你需要继承Exception:

    class EmptyKeyError(Exception):
        pass
    
    try:
        raise EmptyKeyError('Key empty')
    except EmptyKeyError as exc:
        print(exc)
    except Exception:
        print('caught the general exception')
    

    【讨论】:

    猜你喜欢
    • 2021-07-05
    • 1970-01-01
    • 2015-06-07
    • 1970-01-01
    • 2021-05-17
    • 2018-05-16
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    相关资源
    最近更新 更多