When creating apps, one of the important factors is to make sure people know that they get readable error messages. Python allows you to define custom exceptions. In this article, we’ll discuss what custom exceptions are, how you can define custom exceptions in Python, and what are the use cases of user-defined exceptions. Let’s get right into it!
Table of Contents
What is a custom exception in Python?
In the Python Exception Handling tutorial, we discussed what an exception is. Now, why would you need to create a custom exception when Python gives you exceptions and error messages by itself? Look at the example below:
The message box states that there’s a syntax error in the code. And these are the kind of vague error messages that Python displays even to the user when something goes wrong within the code.
The user of your application would not know exactly what happened and how to fix it. And that’s where catching errors and defining custom error messages can help your users know exactly what they should do next to fix the error.
How to define custom exceptions in Python?
Now, there are a few ways to create user-defined exceptions in Python and we’ll go through some of the common ones in this article.
1. Using the assert statement
The assert statement is a conditional error handling keyword that allows you to check for specific criteria to be met. If the condition is not met then it will throw AssertionError.
Let’s take an example here. If you have a program that asks for the age of the user. And you want to ensure that users below the age of 18 do not enter the system. You can obviously make use of the if-else condition in Python.
But to show you an example, here’s how you’d perform the same action and throw an error with the assert statement.
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
2. Raising an Exception
You can raise an existing exception by using the raise keyword. So, you just simply write the 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. We can raise any error you want to with the raise keyword as shown above.
3. Python Custom Exception Class
Why stick to the default methods? To create a custom exception class in Python and define an error message, you need to derive the errors from the Exception class directly.
In the following example, we create custom exception class
UnderAge that is derived from the base class Exception. Similar to how we worked in the assert statement method, we’ll raise an error if the minimum age is not met.
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
And that brings us to the end of this tutorial on creating custom exceptions in Python. This article talks about some of the most common ways to build user-defined user exceptions to make it easier for the end user to understand what went wrong with the program and the next steps that they can take.
To summarize the article, here are the three methods discussed here:
- The assert keyword
- The raise keyword
- And custom exception classes