Prerequisite: This article is an extension to Exception Handling.
In this article, we will try to cover How to Define Custom Exceptions in Python with Examples.
Example:
class CustomError(Exception): pass raise CustomError("Example of Custom Exceptions in Python") Output: CustomError: Example of Custom Exceptions in Python
Python throws errors and exceptions when the code goes 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.
User-Defined Exception in Python
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,
Python3
# 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 ): return ( repr ( self .value)) try : raise (MyError( 3 * 2 )) # Value of Exception is stored in error except MyError as error: print ( 'A New Exception occurred: ' , error.value) |
Output
A New Exception occurred: 6
Customizing Exception Classes
To know more about class Exception, run the code below
Python3
help (Exception) |
Output
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 x.name | | __getattribute__(...) | x.__getattribute__('name') <==> x.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) <==> x.name = value | | __setstate__(...) | | __str__(...) | x.__str__() <==> str(x) | | __unicode__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from BaseException: | | __dict__ | | args | | message
Example 1: 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 classes to handle different types of python raise an exception with message
Python3
# define Python user-defined exceptions class Error(Exception): """Base class for other exceptions""" pass class zerodivision(Error): """Raised when the input value is zero""" pass try : i_num = int ( input ( "Enter a number: " )) if i_num = = 0 : raise zerodivision except zerodivision: print ( "Input value is zero, try again!" ) print () |
Output
Enter a number: 0 Input value is zero, try again!
Example 2: 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.
Python3
# 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 pass class TransitionError(Error): # Raised when an operation attempts a state # transition that's not allowed. def __init__( self , prev, nex, msg): self .prev = prev self . next = nex # Error message thrown is saved in msg self .msg = msg try : raise (TransitionError( 2 , 3 * 2 , "Not Allowed" )) # Value of Exception is stored in error except TransitionError as error: print ( 'Exception occurred: ' , error.msg) |
Output
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.
Python3
# NetworkError has base RuntimeError # and not Exception class Networkerror(RuntimeError): def __init__( self , arg): self .args = arg try : raise Networkerror( "Error" ) except Networkerror as e: print (e.args) |
Output
('E', 'r', 'r', 'o', 'r')