Skip to content
Related Articles

Related Articles

User-defined Exceptions in Python with Examples

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Medium
  • Last Updated : 22 Jun, 2022

Python throws errors and exceptions when there is a code gone wrong, which may cause the program to stop abruptly. Python also provides an exception handling method with the help of try-except. Some of the standard exceptions which are most frequent include IndexError, ImportError, IOError, ZeroDivisionError, TypeError, and FileNotFoundError. A user can create his own error using the exception class.

Prerequisite- This article is an extension to Exception Handling.

Creating User-defined Exception:

Programmers may name their own exceptions by creating a new exception class. Exceptions need to be derived from the Exception class, either directly or indirectly. Although not mandatory, most of the exceptions are named as names that end in “Error” similar to the naming of the standard exceptions in python. For example: 


# A python program to create user-defined exception
# class MyError is derived from super class Exception
class MyError(Exception):
    # Constructor or Initializer
    def __init__(self, value):
        self.value = value
    # __str__ is to print() the value
    def __str__(self):
# Value of Exception is stored in error
except MyError as error:
    print('A New Exception occurred: ', error.value)


('A New Exception occurred: ', 6)

Knowing all about Exception Class:

To know more about class Exception, run the code below 




Help on class Exception in module exceptions:

class Exception(BaseException)
 |  Common base class for all non-exit exceptions.
 |  Method resolution order:
 |      Exception
 |      BaseException
 |      __builtin__.object
 |  Methods defined here:
 |  __init__(...)
 |      x.__init__(...) initializes x; see help(type(x)) for signature
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T
 |  ----------------------------------------------------------------------
 |  Methods inherited from BaseException:
 |  __delattr__(...)
 |      x.__delattr__('name') <==> del
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==>
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  __getslice__(...)
 |      x.__getslice__(i, j) <==> x[i:j]
 |      Use of negative indices is not supported.
 |  __reduce__(...)
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |  __setattr__(...)
 |      x.__setattr__('name', value) <==> = value
 |  __setstate__(...)
 |  __str__(...)
 |      x.__str__() <==> str(x)
 |  __unicode__(...)
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from BaseException:
 |  __dict__
 |  args
 |  message

User Defined class with Multiple Inheritance

In the below article, we have created a class named “Error” derived from the class Exception. This base class is inherited by various user-defined class to handle different types of errors.


# define Python user-defined exceptions
class Error(Exception):
   """Base class for other exceptions"""
class zerodivision(Error):
   """Raised when the input value is zero"""
   i_num = int(input("Enter a number: "))
   if i_num ==0:
      raise zerodivision
except zerodivision:
   print("Input value is zero, try again!")


Enter a number: Input value is zero, try again!

Output – 

Enter a number: Input value is zero, try again!

Deriving Error from Super Class Exception

Superclass Exceptions are created when a module needs to handle several distinct errors. One of the common ways of doing this is to create a base class for exceptions defined by that module. Further, various subclasses are defined to create specific exception classes for different error conditions.


# class Error is derived from super class Exception
class Error(Exception):
    # Error is derived class for Exception, but
    # Base class for exceptions in this module
class TransitionError(Error):
    # Raised when an operation attempts a state
    # transition that's not allowed.
    def __init__(self, prev, nex, msg):
        self.prev = prev = nex
        # Error message thrown is saved in msg
        self.msg = msg
    raise(TransitionError(2,3*2,"Not Allowed"))
# Value of Exception is stored in error
except TransitionError as error:
    print('Exception occurred: ',error.msg)


('Exception occurred: ', 'Not Allowed')

How to use standard Exceptions as a base class?

A runtime error is a class that is a standard exception that is raised when a generated error does not fall into any category. This program illustrates how to use runtime error as a base class and network error as a derived class. In a similar way, an exception can be derived from the standard exceptions of Python.


# NetworkError has base RuntimeError
# and not Exception
class Networkerror(RuntimeError):
    def __init__(self, arg):
        self.args = arg
    raise Networkerror("Error")
except Networkerror as e:
    print (e.args)


('E', 'r', 'r', 'o', 'r')

This article is contributed by Piyush Doorwar. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!