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.
Table of Contents
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.
def input_age(age): try: assert int(age) > 18 except ValueError: return 'ValueError: Cannot convert into int' else: return 'Age is saved successfully' print(input_age('23')) # This will print print(input_age(25)) # This will print print(input_age('nothing')) # This will raise ValueError which is handled print(input_age('18')) # This will raise AssertionError and the the program collapse print(input_age(43)) # This will not print
The output of the following program will be
Age is saved successfully Age is saved successfully ValueError: Cannot convert into int Traceback (most recent call last): File "/home/imtiaz/ExceptionHandling.py", line 13, in print(input_age('18')) # This will raise AssertionError the the program collapse File "/home/imtiaz/ExceptionHandling.py", line 3, in input_age assert int(age) > 18 AssertionError
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
def input_age(age): try: if(int(age)<=18): raise ZeroDivisionError except ValueError: return 'ValueError: Cannot convert into int' else: return 'Age is saved successfully' print(input_age('23')) # This will execute properly print(input_age('18')) # This will not execute properly
The output of the code will be
Age is saved successfully Traceback (most recent call last): File "/home/imtiaz/ExceptionHandling.py", line 12, in print(input_age('18')) # This will not print File "/home/imtiaz/ExceptionHandling.py", line 4, in input_age raise ZeroDivisionError ZeroDivisionError
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.
class UnderAge(Exception): pass def verify_age(age): if int(age) < 18: raise UnderAge else: print('Age: '+str(age)) # main program verify_age(23) # won't raise exception verify_age(17) # will raise exception
And the output will be
So, that’s all about Python custom Exception. Hope, everything is easier to understand. For any further query, please use the comment box below.