Python中的自定义异常

3 投票
1 回答
781 浏览
提问于 2025-04-18 08:41

我正在尝试理解如何在Python中使用自定义异常,主要是通过try-except结构来实现。

这里有一个简单的自定义异常的例子:

# create custom error class
class CustomError1(Exception):
    pass

我试着这样使用它:

# using try-except
def fnFoo1(tuple1, tuple2):
    try:
        assert(len(tuple1) == len(tuple2))
    except AssertionError:
        raise(CustomError1)
    return(1)
fnFoo1((1,2), (1, 2, 3))

这样会引发一个CustomeError1,但同时也会引发一个AssertionError,我希望能够把这个AssertionError包含在CustomError1里面。

下面的代码实现了我想要的效果,但看起来似乎不是处理异常的正确方式。

# use the custom error function without try-catch
def fnFoo2(tuple1, tuple2):
    if len(tuple1) != len(tuple2): raise(CustomError1)
    print('All done!')
fnFoo2((1,2), (1, 2, 3))

那么,如何编写自定义异常来隐藏其他异常呢?

1 个回答

4

根据PEP 409的说明,你可以通过使用raise CustomError1 from None来隐藏原来的错误信息。这一点在这里也有说明:

使用raise new_exc from None实际上是把旧的错误信息替换成新的错误信息,以便于显示。

这个功能是在Python 3.3版本中添加的。在3.0到3.2版本之间,是无法隐藏原来的错误信息的(真是让人头疼)。

撰写回答