Python 有许多内置异常,当程序中出现问题时,这些异常会强制程序输出错误信息。
然而,有时您可能需要创建自定义异常来满足您的目的。
在 Python 中,用户可以通过创建一个新类来定义此类异常。这个异常类必须直接或间接地派生自 Exception 类。大多数内置异常也是从该类派生的。
1: 自定义异常
在这里,我们创建了一个名为 CustomError 的用户自定义异常,它派生于异常类。这个新异常可以像其他异常一样,使用 raise 语句引发,并带有可选的错误信息。
class CustomError(Exception):
pass
x = 1
if x == 1:
raise CustomError('This is custom error')
输出:
Traceback (most recent call last):
File "error_custom.py", line 8, in
raise CustomError('This is custom error')
__main__.CustomError: This is custom error
2: 捕捉自定义异常
本例展示了如何捕获自定义异常
class CustomError(Exception):
pass
try:
raise CustomError('Can you catch me ?')
except CustomError as e:
print ('Catched CustomError :{}'.format(e))
except Exception as e:
print ('Generic exception: {}'.format(e))
输出:
Catched CustomError :Can you catch me ?