Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Built-in Exceptions
Next article icon

User-defined Exceptions in Python with Examples

Last Updated : 04 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, exceptions are used to handle errors that occur during the execution of a program. While Python provides many built-in exceptions, sometimes we may need to create our own exceptions to handle specific situations that are unique to application. These are called user-defined exceptions.

To manage errors and exceptions, Python offers an exception handling mechanism using try and except blocks. Some common exceptions include IndexError, ImportError, IOError, ZeroDivisionError, TypeError and FileNotFoundError.

Creating User-Defined Exceptions

User-defined exceptions are created by defining a new class that inherits from Python’s built-in Exception class or one of its subclasses. By doing this, we can create custom error messages and handle specific errors in a way that makes sense for our application.

Steps to Create and Use User-Defined Exceptions

  • Define a New Exception Class: Create a new class that inherits from Exception or any of its subclasses.
  • Raise the Exception: Use the raise statement to raise the user-defined exception when a specific condition occurs.
  • Handle the Exception: Use try-except blocks to handle the user-defined exception.

Example of a User-Defined Exception:

Python
# Step 1: Define a custom exception class class InvalidAgeError(Exception):     def __init__(self, age, msg="Age must be between 0 and 120"):         self.age = age         self.msg = msg         super().__init__(self.msg)      def __str__(self):         return f'{self.age} -> {self.msg}'  # Step 2: Use the custom exception in your code def set_age(age):     if age < 0 or age > 120:         raise InvalidAgeError(age)     else:         print(f"Age set to: {age}")  # Step 3: Handling the custom exception try:     set_age(150)  # This will raise the custom exception except InvalidAgeError as e:     print(e) 

Output
150 -> Age must be between 0 and 120 

Explanation:

  • InvalidAgeError class inherits from Exception. It has an __init__ method that takes an age and an optional message. __str__ method returns a string that will be shown when the exception is printed.
  • In the set_age function, we check if the age is outside the valid range (0–120). If it is, we raise the InvalidAgeError.
  • We use a try-except block to catch and handle the InvalidAgeError. When this error is raised, the error message is printed.

Customizing Exception Classes

When we create a custom exception, we subclass Python’s built-in Exception class (or a subclass like ValueError, TypeError, etc.). We can then add our own attributes, methods or custom logic to make our exception more informative.

Python
# Step 1: Subclass the Exception class  class InvalidAgeError(Exception):     def __init__(self, age, msg="Age must be between 0 and 120", error_code=1001):         # Custom attributes         self.age = age         self.msg = msg         self.error_code = error_code         super().__init__(self.msg)  # Call the base class constructor      # Step 2: Customize the string representation of the exception          def __str__(self):         return f"[Error Code {self.error_code}] {self.age} -> {self.msg}"  # Step 3: Raising the custom exception  def set_age(age):     if age < 0 or age > 120:         raise InvalidAgeError(age)     else:         print(f"Age set to: {age}")  # Step 4: Handling the custom exception with additional information  try:     set_age(150)  # This will raise the custom exception except InvalidAgeError as e:     print(e) 

Output
[Error Code 1001] 150 -> Age must be between 0 and 120 

Explanation:

  • __str__ method is overridden to provide a custom error message when the exception is printed. Message includes the error code and age, making it more informative.
  • In the set_age function, if the age is invalid, the custom exception InvalidAgeError is raised. Exception is then caught in the try-except block, and the customized error message is printed.

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.

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


Next Article
Python Built-in Exceptions
author
kartik
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

  • Help function in Python
    help() function in Python is a built-in function that provides information about modules, classes, functions and modules. It is useful for retrieving information on various Python objects. Example: [GFGTABS] Python help() [/GFGTABS]OutputWelcome to Python 3.13's help utility! If this is your first t
    5 min read
  • __import__() function in Python
    __import__() is a built-in function in Python that is used to dynamically import modules. It allows us to import a module using a string name instead of the regular "import" statement. It's useful in cases where the name of the needed module is know to us in the runtime only, then to import those mo
    2 min read
  • Python Classes and Objects
    A class in Python is a user-defined template for creating objects. It bundles data and functions together, making it easier to manage and use them. When we create a new class, we define a new type of object. We can then create multiple instances of this object type. Classes are created using class k
    6 min read
  • Constructors in Python
    In Python, a constructor is a special method that is called automatically when an object is created from a class. Its main role is to initialize the object by setting up its attributes or state. The method __new__ is the constructor that creates a new instance of the class while __init__ is the init
    3 min read
  • Destructors in Python
    Constructors in PythonDestructors are called when an object gets destroyed. In Python, destructors are not needed as much as in C++ because Python has a garbage collector that handles memory management automatically. The __del__() method is a known as a destructor method in Python. It is called when
    7 min read
  • Inheritance in Python
    Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a class (called a child or derived class) to inherit attributes and methods from another class (called a parent or base class). This promotes code reuse, modularity, and a hierarchical class structure. In this arti
    7 min read
  • Encapsulation in Python
    In Python, encapsulation refers to the bundling of data (attributes) and methods (functions) that operate on the data into a single unit, typically a class. It also restricts direct access to some components, which helps protect the integrity of the data and ensures proper usage. Table of Content En
    6 min read
  • Polymorphism in Python
    Polymorphism is a foundational concept in programming that allows entities like functions, methods or operators to behave differently based on the type of data they are handling. Derived from Greek, the term literally means "many forms". Python's dynamic typing and duck typing make it inherently pol
    7 min read
  • Class method vs Static method in Python
    In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated
    5 min read
  • File Handling in Python
    File handling refers to the process of performing operations on a file such as creating, opening, reading, writing and closing it, through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely a
    7 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences