[4 Steps] Create User Defined Exception in Python with Example

[4 Steps] Create User Defined Exception in Python with Example

[4 Steps] Create User Defined Exception in Python with Example

Want to create your own defined custom exception in Python?

At the end of this tutorial, you will be able to define your own exception in Python.

Before that, you should know the basic exception handling.

Example for simple exception handing in Python:

When you divide any number by zero, it raises the ‘division by zero’ exception.

Python Program for Exception Handling:

try:
  1/0

except Exception as err:
  # perform any action on Exception instance
  print("Error:", err)

Output:

Error: division by zero

Note: You can also use assert to raise the exception in Python.

If you understand this simple example, creating a user-defined exception is not much difficult.

Python interview questions and answers

Let’s begin with creating your own custom exception.

Create User Defined Exception in Python

Write steps involved in the creation of a user defined exception.

Step 1: Create User-Defined Exception Class

  • Write a new class (says YourException) for custom exception and inherit it from an in-build Exception class.
  • Define function __init__() to initialize the object of the new class. You can add as many instance variables as you want, to support your exception. For simplicity, we are creating one instance variable called message.

Great!

This is how it looks like.

class YourException(Exception):
  def __init__(self, message):
    self.message = message

You have created a simple user-defined exception class.

Step 2: Raising Exception

Now you can write a try-except block to catch the user-defined exception in Python.

For testing, inside the try block, we are raising an exception using a keyword “raise".

raise YourException("Something is fishy")

It creates the instance of the exception class YourException. You can pass any message to your exception class instance.

Step 3: Catching Exception

Now you have to catch the user-defined exception using except block.

except YourException as err:
  print(err.message)

We are catching a user-defined exception called YourException.

Step 4: Write a Program for User-Defined Exception in Python

Let’s club all these steps. Here is what the complete program looks like.

class YourException(Exception):
  def __init__(self, message):
    self.message = message

try:
  raise YourException("Something is fishy")

except YourException as err:
  # perform any action on YourException instance
  print("Message:", err.message)

Output:

Message: Something is fishy

Congrats you have defined your own exception in Python!

Python makes things very simple, isn’t it?

Here is one more thing you can try for handling a user-defined exception.

You can define multiple instance variables for the newly created exception class. With this, you can pass multiple values while raising exceptions.

In the below example, along with the error message we are also defining the level of difficulty for exceptions.

class YourException(Exception):
  def __init__(self, message, level):
    self.message = message
    self.level = level

try:
  raise YourException("Something is fishy", "Level 5")

except YourException as err:
  # perform any action on YourException instance
  print("Message:", err.message)
  print("Difficulty Level: ", err.level)

Output:

Message: Something is fishy
Difficulty Level: Level 5

This is the simple way of creating a user-defined exception in Python. If you have any question, let me know in the comment.

Leave a Reply

Your email address will not be published. Required fields are marked *