Python Custom Exception With Examples

In this tutorial we are going to learn about Python Custom Exception. If you don’t know about Python Exception Handling, we suggest you to read the previous tutorial.

Python Custom Exception

In Python Exception Handling Tutorial, we discussed about what exception is. Basically exception means when things are not going accordingly. We talked about different kind of built-in exceptions in the previous tutorial. However sometimes built-in exceptions are not enough for our need, then we can define our own custom exception.

Python Custom Exception using assert statement

Using assert statement you can initially create your own exception. Basically assert statement check for a condition. If the condition is not met then it will throw AssertionError. Suppose you wrote a function where you take age as an argument. You don’t want to let programmers use the function if the age is less the 18. So the function would be.

The output of the following program will be

Raising an Exception

Your can raise an existing exception by using raise keyword. So, you just simply write raise keyword and then the name of the exception. If we modify the previous code, we get

The output of the code will be

Though, the exception was not due to divide by zero, still we see it. Because we raised ZeroDivisionError.

Python Custom Exception Class

Python allow programmers to create their own exception class. Exceptions should typically be derived from the Exception class, either directly or indirectly. In the following example, we create custom exception class UnderAge that is derived from the base class Exception.

Again, in another method we raised the UnderAge exception if the condition is not met. The following code will give you some insight about the idea.

And the output will be

Python Custom Exception

So, that’s all about Python custom Exception. Hope, everything is easier to understand. For any further query, please use the comment box below.

Reference: Python User Defined Exception Official Documentation

By admin

Leave a Reply