Python Custom Exceptions
Python Custom Exceptions are user-defined exceptions that inherit from the built-in Exception
class or another subclass of Exception
.
By defining a custom exception, you can provide more descriptive error messages and handle exceptional situations in a way that is meaningful to your particular application.
How to define a Custom Exception
In Python, you can define custom exceptions by creating a new class that is derived from the built-in Exception
class.
The syntax to define custom exceptions is the following:
class MyCustomException(Exception):
...
pass
then you can raise this custom exception, using the raise
statement:
raise MyCustomException("This is a custom error message.")
- When you are developing a large Python program, it is a good practice to place all the user-defined exceptions that your program raises in a separate file.
- Many standard modules define their exceptions separately as
exceptions.py
orerrors.py
(generally but not always).
Example
Let's define a custom exception called InvalidAgeException
.
This exception is raised when a user enters an age under 18, which would indicate an invalid voting age.
# define Python user-defined exceptions
class InvalidAgeException(Exception):
"Raised when the input value is less than 18"
pass
# you need to guess this number
min_allowed_age = 18
try:
age = int(input("Enter your age: "))
if age < min_allowed_age:
raise InvalidAgeException
else:
print("Eligible to Vote")
except InvalidAgeException:
print("Exception occurred: Invalid Age")
So, if the input of the user is greater than 18, then:
Enter a number: 25
Eligible to Vote
If the input of the user is smaller than 18, then:
Enter a number: 15
Exception occurred: Invalid Age
Customizing Exception Classes
You can also add attributes and methods to custom exceptions, similar to regular classes.
For example, you can override the __str__
method to customize the string representation of the exception, or add additional data that can be accessed when the exception is caught:
class MyCustomException(Exception):
def __init__(self, message, custom_data):
super().__init__(message)
self.custom_data = custom_data
def __str__(self):
return f"{super().__str__()} - Additional Info: {self.custom_data}"
Raising and handling this custom exception will look like this:
try:
raise MyCustomException("An error occurred", {"detail": "Some detailed info"})
except MyCustomException as e:
print(e) # Outputs: An error occurred - Additional Info: {'detail': 'Some detailed info'}
The inherited __str__
method of the Exception class is then used to display the corresponding message when MyCustomException is raised.