The Wayback Machine - https://web.archive.org/web/20241009195058/https://www.geeksforgeeks.org/user-defined-exceptions-python-examples/
Open In App

User-defined Exceptions in Python with Examples

Last Updated : 15 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

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
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 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
7 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
5 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
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 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
Concrete Exceptions in Python
In Python, exceptions are a way of handling errors that occur during the execution of the program. When an error occurs Python raises an exception that can be caught and handled by the programmer to prevent the program from crashing. In this article, we will see about concrete exceptions in Python in detail with the help of examples. Concrete Excep
3 min read
Define Custom Exceptions in Python
In Python, exceptions occur during the execution of a program that disrupts the normal flow of the program’s instructions. When an error occurs, Python raises an exception, which can be caught and handled using try and except blocks. Here’s a simple example of handling a built-in exception: [GFGTABS] Python try: result = 10 / 0 except ZeroDivisionE
3 min read
Errors and Exceptions in Python
Errors are problems in a program that causes the program to stop its execution. On the other hand, exceptions are raised when some internal events change the program's normal flow.  Table of Content Syntax Errors in PythonPython Logical Errors (Exception)Common Builtin ExceptionsError HandlingSyntax Errors in PythonWhen the proper syntax of the lan
4 min read
How to Catch Multiple Exceptions in One Line 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 to handle exceptions we use try/Except metho
2 min read
Scrapy - Exceptions
Python-based Scrapy is a robust and adaptable web scraping platform. It provides a variety of tools for systematic, effective data extraction from websites. It helps us to automate data extraction from numerous websites. Scrapy Python Scrapy describes the spider that browses websites and gathers data in a clear and concise manner. The spider is in
7 min read
How to fix 'django.core.exceptions.FieldDoesNotExist'
In this article we will explore how we can fix / solve the django.core.exceptions.FieldDoesNotExist' error This exception raised by Django indicates that the field we are trying to access or modify is not exist. There may be some typo mistakes, field may not be there. So in this article we are looking for the solutions to fix this error. What is 'd
4 min read
How to fix - django.core.exceptions.ImproperlyConfigured
In this article, we will explore how to resolve the `django.core.exceptions.ImproperlyConfigured` error in Django. We'll discuss possible solutions and approaches for handling this error, providing a thorough explanation along with examples. What is 'django.core.exceptions.ImproperlyConfigured'?`django.core.exceptions.ImproperlyConfigured` is an ex
4 min read
How to check whether a file exists without exceptions?
When working with files in Python, it’s often necessary to check if a file exists before attempting to read from or write to it. While exception handling using try and except blocks is a common approach, Python provides cleaner and more intuitive methods to achieve this. In this article, we will explore various ways to check for file existence with
2 min read
Python | Sorting string using order defined by another string
Given two strings (of lowercase letters), a pattern and a string. The task is to sort string according to the order defined by pattern and return the reverse of it. It may be assumed that pattern has all characters of the string and all characters in pattern appear only once. Examples: Input : pat = "asbcklfdmegnot", str = "eksge" Output : str = "g
2 min read
Python VLC Instance - Enumerate the defined audio output devices
In this article we will see how we can get the enumerate audio output devices from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance obje
3 min read
Viewing all defined variables in Python
In this article, we are going to discuss how to view all defined variables in Python. Viewing all defined variables plays a major role while debugging the code. Method 1: Using dir() function dir() is a built-in function to store all the variables inside a program along with the built-in variable functions and methods. It creates a list of all decl
5 min read
Why do Python lambda defined in a loop with different values all return the same result?
In this article, we are going to learn why Python lambda defined in a loop with different values all return the same result. In this article, we will explore the reasons behind this behavior and discuss how to avoid it. We will start by looking at how lambda functions are defined and executed, and how they capture the values of variables that are u
6 min read
Python - Check if String Contain Only Defined Characters using Regex
In this article, we are going to see how to check whether the given string contains only a certain set of characters in Python. These defined characters will be represented using sets. Examples: Input: ‘657’ let us say regular expression contains the following characters- (‘78653’) Output: Valid Explanation: The Input string only consists of charac
2 min read
Nameerror: name self is not defined in Python
Python, a dynamically typed and object-oriented programming language, is lauded for its simplicity and readability. However, even the most seasoned developers can encounter stumbling blocks, and one such common hurdle is the "NameError: name 'self' is not defined." In this article, we will see how to fix Nameerror: Name 'self' is not defined in Pyt
4 min read
Nameerror: Name '__File__' Is Not Defined" in Python
One common issue that developers encounter is the "NameError: name 'file' is not defined." This error typically occurs when trying to access the __file__ attribute in a context where it is not recognized. In this article, we'll explore what this error means and discuss three scenarios where it might occur What is Nameerror?The __file__ attribute is
4 min read
How to fix 'Variable not defined' in custom modules in Python
Encountering the 'Variable not defined' error in Python can be frustrating, especially when working with custom modules. This error indicates that Python cannot find a variable that you are trying to use. In this article, we will explore what this error means, its common causes, and the steps to resolve it. Understanding the 'Variable not Defined'
5 min read
How to Fix "NameError: name 'os' is not defined" in Python
If we are working with Python and encounter an error that says "NameError: name 'os' is not defined", then we need not worry, it is a very common issue, and fixing this error is very simple. This error usually occurs when we try to use the os module without importing it first. In this article, we will learn what this error means, and how we can fix
3 min read
How to Fix: NameError name ‘pd’ is not defined
In this article we will discuss how to fix NameError pd is not defined in Python. When we imported pandas module without alias and used pd in the code, the error comes up. Example: Code to depict error C/C++ Code # import pandas module import pandas # create dataframe data = pd.DataFrame({'a': [1, 2], 'b': [3, 4]}) # display data Output: ----------
2 min read
How to Fix: NameError name ‘np’ is not defined
In this article, we will discuss how to fix NameError np that is not defined in Python. When we imported the NumPy module without alias and used np in the code, the error comes up. Example: Code to depict error C/C++ Code # import numpymodule import numpy # create numpy array a = np.array([1, 2, 3, 45]) # display a Output: name 'np' is not defined
2 min read
Difference between Normal def defined function and Lambda
In this article, we will discuss the difference between normal def defined function and lambda in Python. Def keyword​​​​​​​In python, def defined functions are commonly used because of their simplicity. The def defined functions do not return anything if not explicitly returned whereas the lambda function does return an object. The def functions m
2 min read
Fetch top 10 starred repositories of user on GitHub | Python
Prerequisites: Basic understanding of python, urllib2 and BeautifulSoup We often write python scripts to make our task easier, so here is the script which helps you to fetch top 10 starred repositories of any user on GitHub.You just need Github username (For example: msdeep14) to run the script.Script Explanation: First access the repository url of
4 min read
Python | User groups with Custom permissions in Django
Let's consider a trip booking service, how they work with different plans and packages. There is a list of product which subscriber gets on subscribing to different packages, provided by the company. Generally, the idea they follow is the level-wise distribution of different products. Let's see the different packages available on tour booking servi
4 min read
Article Tags :
Practice Tags :