自定义一个完整的多种错误的异常类
时间: 2024-04-08 14:30:32 浏览: 17
当然可以!下面是一个示例,展示了如何自定义一个完整的多种错误的异常类:
```python
class CustomException(Exception):
def __init__(self, error_code, error_message):
self.error_code = error_code
self.error_message = error_message
super().__init__(self.error_message)
class InvalidInputException(CustomException):
def __init__(self, error_message):
super().__init__(400, error_message)
class NotFoundException(CustomException):
def __init__(self, error_message):
super().__init__(404, error_message)
class ServerErrorException(CustomException):
def __init__(self, error_message):
super().__init__(500, error_message)
```
在这个示例中,我们定义了一个基础的自定义异常类`CustomException`,它接受一个错误代码和错误信息作为参数,并将其传递给父类`Exception`的构造函数。
然后,我们定义了三个具体的异常类`InvalidInputException`,`NotFoundException`和`ServerErrorException`,它们分别继承自`CustomException`。这些具体的异常类可以用于表示不同类型的错误,例如无效输入、找不到资源和服务器内部错误。
你可以根据需要添加更多的自定义异常类,并在每个类中定义适合的错误代码和错误信息。这样,当出现相应的错误时,你可以抛出相应的异常,并在处理异常时获得有关错误的详细信息。