How to create custom exceptions in Python

Handling exceptions in any application is a very critical step. Exceptions help to handle any runtime error that can crash your application. In Python, there are many built-in exceptions like:

  • ArithmeticError
  • SyntaxError
  • FileNotFoundError
  • ZeroDivisionError

But many times, you would need to create your own custom exceptions too. You can define your own custom exceptions by creating a class that is derived from the built-in Exception class. Take a look at the code below:

class NotValidAge(Exception):
"""Raised when the age is less than 18"""
pass
def driving_license(age):
if age < 18:
raise NotValidAge
driving_license(17)

Explanation:

  • In line 1, we created the NotValidAge class, which inherits from the Exception class. We will use the NotValidAge exception when the age is below 18 years.

  • From lines 5 to 7, we created a function that raises an exception (NotValidAge) if the age is less than 18 years.

  • In line 9, we called that function and saw that our custom exception was raised.

You can customize the exception message by overriding the __str__() method. (This method is used by Exception to print the message). Let’s take a look at how we can do this.

class NotValidAge(Exception):
"""Raised when the age is less than 18"""
def __str__(self):
return "Age should be greater than 18 years."
def driving_license(age):
if age < 18:
raise NotValidAge
driving_license(17)

Explanation:

  • In line 1, we created the NotValidAge class, which inherits from the Exception class. We will use the NotValidAge exception when the age is below 18 years.

  • In line 3, we overrode the __str__() method and returned our own message. This message is going to be displayed when this exception occurs.

  • From lines 6 to 8, we created a function that raises an exception (NotValidAge) if the age is less than 18 years.

  • In line 10, we called that function and saw that our custom exception was raised with our custom message.

In this way, we can create our own custom exceptions with custom messages.

Free Resources