Custom exceptions in Python with examples

Python throws errors and exceptions when the code fails, which can cause the program to stop abruptly. Python also provides a try-exc method to handle exceptions. Some of the standard exceptions that are the most common include IndexError, ImportError, IOError, ZeroDivisionError, TypeError, and FileNotFoundError. The user can create his own error using the exception class.

Creating a custom exception

Programmers can name their own exceptions by creating a new exception class. Exceptions must be obtained from the Exception class, directly or indirectly. Although not required, most exceptions are named as names ending in “Error”, similar to python`s standard exceptions. For example:

# Python program for creating custom exceptions

# class MyError derives from superclass exceptions

class MyError (Exception):


# Constructor or initializer

def __ init __ ( self , value):

self . value = value


# __str__ should print () the value

def __ str __ ( self ):

return ( repr ( self . value))


try :

raise (MyError ( 3 * 2 ))

# The value of the exception is stored in the error

except MyError as error:

  print ( ` A New Exception occured: ` , error.value)


 (`A New Exception occured:`, 6) 

Knowing all about the exceptional class

To learn more about the Exception class, run the code below

help (Exception)

Error getting from Super Class exception

Superclass exceptions are thrown when a module needs to handle several different errors. One of the common ways to do this — create a base class for the exceptions defined by this module. In addition, different subclasses are defined to create specific exception classes for different error conditions.

# class The error is derived from Superclass Exception

class Error (Exception):


# The error is an exception derived class, but

# Base class for exceptions in this module



class TransitionError (Error):


  # Occurs when an operation tries state

# jump that is not allowed.

def __ init __ ( self , prev, nex, msg):

self . prev = prev

self . next = nex


# Generated message about error is saved in the message

self . msg = msg

try :

raise (TransitionError ( 2 , 3 * 2 , " Not Allowed " ))

# Exception value stored in error

except TransitionError as error:

print ( `Exception occured:` , error.msg)


 (`Exception occured:`, `Not Allowed`) 

How to use standard exceptions as a base class?

Runtime error — this is a standard class exception that is thrown when the generated error does not fall into any category. This program illustrates how to use runtime errors as a base class and network errors as a derived class. Similarly, any exception can be thrown from Python standard exceptions.

# NetworkError has a base RuntimeError
# not an exception

class Networkerror (RuntimeError):

def __ init __ ( self , arg):

self . args = arg


try :

raise Networke rror ( "Error" )


except Networkerror as e:

print (e.args)


 (`E`,` r`, `r`,` o`, `r`) 

This article is provided by Piyush Doorvar . If you are as Python.Engineering and would like to contribute, you can also write an article using or by posting an article contribute @ See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.