Custom Exception in Python

Custom Exception in Python

In this article, I am going to discuss Custom Exception in Python with examples. Please read our previous article where we discussed Nested try-except-finally blocks in Python. As part of this article, we are going to discuss the following pointers in details.

Predefined Exceptions in Python

The exceptions which we handled in the examples till now are predefined ones. They are already available builtin exceptions. If any exception occurs, then Python Virtual Machine will handle those exceptions using the predefined exceptions. Examples of predefined exceptions are ZeroDivisionError, ValueError, NameError etc.

Custom Exceptions in Python:

Sometimes based on project requirement, a programmer needs to create his own exceptions and raise explicitly for corresponding scenarios. Such types of exceptions are called customized Exceptions or Programmatic Exceptions. We can raise a custom exception by using the keyword ‘raise’.

Steps to create Custom Exception in python:

The first step is to create a class for our exception. Since all exceptions are classes, the programmer is supposed to create his own exception as a class. The created class should be a child class of in-built “Exception” class.

Syntax

Steps to create Custom Exception in python

In the second step raise the exception where it required. When the programmer suspects the possibility of exception, then he can raise his own exception using raise keyword

Syntax:

How to create Custom Exceptions in python

Program: Creating Custom Exception in Python (demo39.py)
class NegativeError(Exception):
   def __init__(self, data):
       self.data = data

try:
   x = int(input("Enter a number between positive integer: "))
   if x < 0:
       raise NegativeError(x)
except NegativeError as e:
   print("You provided {}. Please provide positive integer values only".format(e))

Output:

Creating Custom Exception in Python

Program: Custom Exceptions in Python (demo40.py)
class TooYoungException(Exception):
   def __init__(self, arg):
       self.msg=arg
class TooOldException(Exception):
   def __init__(self, arg):
       self.msg=arg

age=int(input("Enter Age:"))
if age>60:
   raise TooOldException("Your age already crossed marriage age...no chance of getting marriage")
elif age<18:
   raise TooYoungException("Plz wait some more time you will get best match soon!!!")
else:
   print("You will get match details soon by email!!!")

Output:

Custom Exceptions in Python

Custom Exceptions in Python

In the next article, I am going to discuss Working with Files in Python with Examples. Here, in this article, I try to explain Custom Exceptions in Python with Examples. I hope you enjoy this Custom Exceptions in Python article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

2 thoughts on “Custom Exception in Python”

  1. in demo39.py,why we writing a constructor in class without that also code is executing.
    class NegativeError(Exception):
    def __init__(self, data):
    self.data = data

Leave a Reply

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