Python中的自定义异常
我正在尝试理解如何在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))
那么,如何编写自定义异常来隐藏其他异常呢?