有时我们希望创建属于自己的异常。在Python中,Python的异常处理都是继承自Exception。因此我们自定义的异常类也通过继承Exception来实现。
# 自定义异常class FError(Exception):pass# 抛出异常try:raise FError("my exception")except FError as e:print(e)# 打印结果是 my exception
以下是一个简单的自定义异常类模板
class CustomError(Exception):def __init__(self, ErrorInfo):super().__init__(self)self.errorinfo=ErrorInfodef __str__(self):return self.errorinfoif __name__ == '__main__':try:raise CustomError('customer exception')except CustomError as e:print(e)# 打印结果是customer exception
