Create and Catch a Custom Exception in Python
A minimal Python example demonstrating how to define, raise, and catch a custom exception class by subclassing Exception.
Python projects · Python fundamentals
Start here
Read the requirements and any configuration below, then follow the usage example. Source paths below are relative to the repository root; run commands from the working directory stated in Usage. This example’s source is in Custom Exception/Console_Code/. Install any third-party packages in an isolated Python environment.
Overview
This script shows the pattern for creating a user-defined exception in Python by subclassing the built-in Exception class. It demonstrates how to raise the custom exception under a specific condition and catch it with a try/except block.
Usage
From the Console_Code folder:
python CustomException.py
Output (confirmed by running the script):
Something went wrong
How It Works
CustomExceptionis defined as a subclass ofException, accepting amessageparameter.some_function()raisesCustomExceptionwhen a condition is met (x < y).- The exception is caught in a
try/exceptblock, and the message is printed.
Code Example
class CustomException(Exception):
def __init__(self, message):
super().__init__(message)
self.message = message
def some_function():
x = 5
y = 6
if x < y:
raise CustomException("Something went wrong")
try:
some_function()
except CustomException as e:
print(e.message)
FAQ
Do I need to store message on the exception?
No — str(e) already returns the message passed to super().__init__(message). Storing it as self.message simply makes it available as a named attribute, which is handy when you add more fields (such as an error code).
Should custom exceptions inherit from Exception or BaseException?
From Exception (or one of its subclasses). BaseException is reserved for exceptions such as KeyboardInterrupt and SystemExit that ordinary except Exception blocks should not catch.
Architecture
Custom Exception/
└── Console_Code/
└── CustomException.py # Main script
Troubleshooting and limitations
- No external dependencies required — uses only Python built-ins.
- The script includes a discussion in the docstring about when it is appropriate to make a custom exception serializable (relevant for distributed systems where exceptions may be passed across process boundaries).
Related documentation
Documentation links
Read all Python Projects and Code Examples guides online · Project overview · All developer projects