In python we can create our custom exception and raise it. In this tutorial, we will introduce to you on how to create our custom exception and how to raise it.
Create a custom exception
To create a custom exception in python, you should inherit Exception class.
Here is an example.
class CustomException(Exception): def __init__(self,ErrorInfo): super().__init__(self) # init parent class self.errorinfo=ErrorInfo def __str__(self): return self.errorinfo
In this example, we only add some error message on our custom exception, you can set different exception message based on different condition.
Raise custom exception
To rasie an exception in python, we should use raise statement.
Here is an example to show how to raise our custom exception.
if __name__ == '__main__': try: raise CustomException('custom exception') except CustomException as e: print(e)
In this example, we use try except statement to catch our custom exception and use print() functon to display our custom exception message: custom exception