Open In App

User-defined Exceptions in Python with Examples

Last Updated : 15 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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')


Previous Article
Next Article

Similar Reads

Python User defined functions
A function is a set of statements that take inputs, do some specific computation, and produce output. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can call the function. Functions that readily come with Python are called built
6 min read
User Defined Data Structures in Python
In computer science, a data structure is a logical way of organizing data in computer memory so that it can be used effectively. A data structure allows data to be added, removed, stored and maintained in a structured manner. Python supports two types of data structures: Non-primitive data types: Python has list, set, and dictionary as its non-prim
4 min read
Sorting objects of user defined class in Python
The following article discusses how objects of a user-defined class can be arranged based on any of the variables of the class, which obviously will hold some value for every object. So far, we are aware of how we can sort elements of a list, the concept here is more or less the same as, except it is a step forward or we can say it is an advanced v
4 min read
How to Write Spark UDF (User Defined Functions) in Python ?
In this article, we will talk about UDF(User Defined Functions) and how to write these in Python Spark. UDF, basically stands for User Defined Functions. The UDF will allow us to apply the functions directly in the dataframes and SQL databases in python, without making them registering individually. It can also help us to create new columns to our
4 min read
Python | Catching and Creating Exceptions
Catching all exceptions is sometimes used as a crutch by programmers who can’t remember all of the possible exceptions that might occur in complicated operations. As such, it is also a very good way to write undebuggable code. Because of this, if one catches all exceptions, it is absolutely critical to log or reports the actual reason for the excep
2 min read
Exceptions - Selenium Python
Exceptions in Selenium Python are the errors that occur when one of method fails or an unexpected event occurs. All instances in Python must be instances of a class that derives from BaseException. Two exception classes that are not related via subclassing are never equivalent, even if they have the same name. The built-in exceptions can be generat
3 min read
Errors and Exceptions in Python
Errors are the problems in a program due to which the program will stop the execution. On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program. Two types of Error occurs in python. Syntax errorsLogical errors (Exceptions) Syntax errors When the proper syntax of the language is not follow
3 min read
Python - Catch All Exceptions
In this article, we will discuss how to catch all exceptions in Python using try, except statements with the help of proper examples. But before let's see different types of errors in Python. There are generally two types of errors in Python i.e. Syntax error and Exceptions. Let's see the difference between them. Difference between Syntax Error and
3 min read
How to Catch Multiple Exceptions in One Line in Python?
Prerequisites: Exception handling in python There might be cases when we need to have exceptions in a single line. In this article, we will learn about how we can have multiple exceptions in a single line. We use this method to make code more readable and less complex. Also, it will help us follow the DRY (Don't repeat code) code method Generally t
1 min read
How To Fix Valueerror Exceptions In Python
Python comes with built-in exceptions that are raised when common errors occur. These predefined exceptions provide an advantage because you can use the try-except block in Python to handle them beforehand. For instance, you can utilize the try-except block to manage the ValueError exception in Python. In this article, we will see some methods and
4 min read
Article Tags :
Practice Tags :