Example:
x = 10 / 0 # Raises ZeroDivisionError
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
.
try:
result = 10 / 0
except Exception as e:
print("An error occurred:", e)
Output:
An error occurred: division by zero
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
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)
MyCustomError
inherits from Exception
.
The constructor __init__
takes a custom message.
We use super().__init__
to pass this message to the base class.
Let’s break it down step by step:
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.
except MyCustomError as e:
Python matches the type of exception.
It binds the raised error to variable e
.
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)
Error: Division error | File: script.py | Line: 20
Extracts error message.
Retrieves line number and filename where the error occurred.
Shows enhanced traceback with custom formatting.
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
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 |