To define a custom exception in Python, create a new class, and inherit the Exception class with the new class.
Custom exceptions are also known as user-defined exceptions.
The Exception class is the base class for all the exceptions in Python.
class CustomExceptionError(Exception):
...
pass
try:
...
except CustomExceptionError:
...
Here in the above code syntax, the CustomExceptionError class is a user-defined class inherited by the Python Exception class.
class InvalidAgeException(Exception):
# Raise exception when the age is less than 18.
pass
age = 18
try:
if age < 18:
raise InvalidAgeException()
else:
print("Person is eligible to vote.")
except InvalidAgeException:
print("Person is not eligible to vote.")
Person is eligible to vote.
Here in the above example, we have created a separate class for custom exceptions and inherited them from the Python Exception class.
In the try block, check if the person age is less than 18 (age < 18), then raise the invalid age custom exception class, otherwise print "Person is eligible for vote".
If the age is less than 18 (age < 18), then it raises an invalid age exception, then it skips the rest of the code in a try block and executes the except block.
If the person age is greater than or equal to 18, then the program runs smoothly and does not raise any exceptions.
You can customise the custom exception class and pass arguments in the custom exception class.
class InvalidAgeException(Exception):
# Raise exception when the age is less than 18.
def __init__(self, message = "Not eligible to vote."):
self.message = message
super().__init__(self.message)
age = 18
try:
if age < 18:
raise InvalidAgeException("The person is not eligible to vote.")
else:
print("Person is eligible to vote.")
except InvalidAgeException:
print("Person is not eligible to vote.")
Person is eligible to vote.
Here in the above example, we customise the custom exception class and declare the message parameter in the class constructor function. And also passed that message parameter to the Python Exception class constructor function by using super() function.
While calling the invalid age exception class, we are passing text message as an input parameter in the class. When the person age is less than 18 (age < 18), then the except block will execute and print the passed text message.