In this article Learn Exception Hierarchy in Python and how to add custom exceptions. Understand BaseException, Exception classes, and how to create and raise user-defined exceptions with examples.

Hierarchy of Exceptions and Adding Exceptions in Python

Introduction

In Python, exceptions are special errors that interrupt the normal flow of a program when something goes wrong — for example, dividing by zero, accessing an invalid list index, or opening a missing file.

All these exceptions are organized in a hierarchical structure (like a family tree) so that one type of exception can inherit properties of another.

What is an Exception Hierarchy?

Python exceptions are classes organized under the BaseException class.
This structure helps Python understand what type of error has occurred and allows programmers to handle specific or general exceptions as needed.

For example:

  • ZeroDivisionError is a type of ArithmeticError,
  • and ArithmeticError is a subclass of the general Exception class.

This means handling Exception will also catch ZeroDivisionError.

Exception Hierarchy Diagram (Text Representation)

BaseException

├── SystemExit

├── KeyboardInterrupt

├── GeneratorExit

└── Exception

    ├── ArithmeticError

    │   ├── ZeroDivisionError

    │   ├── OverflowError

    │   └── FloatingPointError

    │

    ├── LookupError

    │   ├── IndexError

    │   └── KeyError

    │

    ├── AssertionError

    ├── AttributeError

    ├── EOFError

    ├── FileNotFoundError

    ├── ImportError

    ├── ModuleNotFoundError

    ├── MemoryError

    ├── NameError

    ├── OSError

    ├── RuntimeError

    ├── TypeError

    ├── ValueError

    └── Warning

Explanation of Key Exception Classes

Exception Class Description
BaseException The root (parent) of all exception classes in Python.
Exception The base class for all standard errors used in programs.
ArithmeticError Base class for mathematical errors.
ZeroDivisionError Raised when dividing a number by zero.
OverflowError Raised when a calculation exceeds the range.
LookupError Raised when an invalid index or key is accessed.
IndexError Raised when accessing an invalid list index.
KeyError Raised when accessing a missing dictionary key.
FileNotFoundError Raised when a file is not found.
TypeError Raised when an operation is applied to an object of the wrong type.
ValueError Raised when a function receives an invalid value.

Example: Handling Multiple Exceptions

try:

    x = int(input(“Enter a number: “))

    y = 10 / x

    print(“Result:”, y)

except ZeroDivisionError:

    print(“Error: Division by zero is not allowed.”)

except ValueError:

    print(“Error: Please enter only numeric values.”)

except Exception as e:

    print(“Other Error:”, e)

finally:

    print(“Execution completed.”)

Output Example

Enter a number: 0

Error: Division by zero is not allowed.

Execution completed.

Adding Exceptions (User-Defined or Custom Exceptions)

Python allows you to create your own exception classes for specific situations where the built-in exceptions are not sufficient.

Syntax:

class MyError(Exception):

    pass

Here, MyError is a user-defined exception that inherits from Python’s built-in Exception class.

Example 1: Custom Exception

class NegativeNumberError(Exception):

    “””Raised when a negative number is entered”””

    pass

try:

    num = int(input(“Enter a positive number: “))

    if num < 0:

        raise NegativeNumberError(“Negative numbers are not allowed.”)

    print(“You entered:”, num)

except NegativeNumberError as e:

    print(“Custom Exception:”, e)

 Output:

Enter a positive number: -5

Custom Exception: Negative numbers are not allowed.

Example 2: Raise and Handle Custom Exception

class AgeLimitError(Exception):

    “””Raised when age is below 18″””

    pass

try:

    age = int(input(“Enter your age: “))

    if age < 18:

        raise AgeLimitError(“Age must be 18 or above to continue.”)

    print(“Access granted!”)

except AgeLimitError as e:

    print(“Error:”, e)

Output:

Enter your age: 15

Error: Age must be 18 or above to continue.

Key Points to Remember

Concept Description
BaseException The root class of all Python exceptions.
Exception Parent class for most runtime errors.
Specific Error Classes Handle specific problems (e.g., ValueError, IndexError).
Custom Exceptions User-defined exceptions for specific conditions.
raise Statement Used to manually raise an exception.
except Exception as e Captures the error message in variable e.

Summary

  • All Python exceptions are derived from BaseException.
  • Built-in exceptions cover most errors, but you can add your own using custom classes.
  • Exception hierarchy helps in organized error handling and allows developers to catch specific or general exceptions.
  • Always use finally for cleanup and raise for manual exception generation.

Conclusion

Understanding the exception hierarchy and creating custom exceptions makes Python programs more reliable and professional.
It allows precise control over error management and helps maintain the flow of execution even during unexpected events.

Some More: 

POP- Introduction to Programming Using ‘C’

DS – Data structure Using C

OOP – Object Oriented Programming 

Java Programming

DBMS – Database Management System

RDBMS – Relational Database Management System

https://defineinfoloop.blogspot.com/?m=1

Leave a Reply

Your email address will not be published. Required fields are marked *