Some text some message..
Back 🔹 What is an Exception in Python? 12 Jul, 2025

An exception is an error that occurs during the execution of a program. When such an error occurs, Python stops the normal flow of the program and raises an exception.

Example:

x = 10 / 0  # Raises ZeroDivisionError

🔹 Python's Exception Class (Base Class)

In Python, all built-in exceptions are derived from the BaseException class. The most commonly used base class for user-defined and system exceptions is the Exception class.

BaseException
 └── Exception
      ├── ArithmeticError
      ├── LookupError
      ├── ImportError
      └── etc.

You can catch any exception using except Exception.


🔹 Catching Exceptions

try:
    result = 10 / 0
except Exception as e:
    print("An error occurred:", e)

Output:

An error occurred: division by zero

🔹 Why Use Classes for Exceptions?

You can define your own custom exceptions by extending the Exception class. This allows for:

  • More descriptive error handling

  • Better control over exception types

  • Custom data passed with the exception


🔹 Creating a Custom Exception Using Class

class MyCustomError(Exception):
    def __init__(self, message):
        super().__init__(message)
        self.message = message

try:
    raise MyCustomError("Something went wrong in custom logic.")
except MyCustomError as e:
    print("Caught a custom error:", e.message)

Explanation:

  • MyCustomError inherits from Exception.

  • The constructor __init__ takes a custom message.

  • We use super().__init__ to pass this message to the base class.


🔹 How Custom Exceptions Work Internally

Let’s break it down step by step:

1. Raising the Exception

raise MyCustomError("Invalid data")

When this line is executed:

  • Python creates an instance of MyCustomError.

  • The __init__() method is called.

  • Control jumps to the nearest matching except block.

2. Catching the Exception

except MyCustomError as e:
  • Python matches the type of exception.

  • It binds the raised error to variable e.


🔹 Example with More Details

import sys

class DetailedException(Exception):
    def __init__(self, message, error_details: sys):
        super().__init__(message)
        self.message = message
        _, _, exc_tb = error_details.exc_info()
        self.file_name = exc_tb.tb_frame.f_code.co_filename
        self.line_number = exc_tb.tb_lineno

    def __str__(self):
        return f"Error: {self.message} | File: {self.file_name} | Line: {self.line_number}"

try:
    a = 10 / 0
except Exception as e:
    raise DetailedException("Division error", sys)

Output:

Error: Division error | File: script.py | Line: 20

What This Does:

  • Extracts error message.

  • Retrieves line number and filename where the error occurred.

  • Shows enhanced traceback with custom formatting.


✅ When to Use Custom Exception Classes?

Use custom exceptions when:

  • You want to signal specific errors (e.g., InvalidAgeError, InsufficientBalanceError)

  • You want to pass additional context

  • You want clean and structured error management in large projects


🔚 Summary

Concept Purpose
Exception Base class for most errors
try-except Catch and handle errors
raise Trigger an exception
Custom Exception Class Add structure and meaning to your error logic