⬅ Previous Topic
Python Exception HandlingNext Topic ⮕
Python Object-Oriented Programming⬅ Previous Topic
Python Exception HandlingNext Topic ⮕
Python Object-Oriented ProgrammingIn Python, not every error fits into the neat boxes of ValueError
, IndexError
, or TypeError
. Sometimes, your program has its own rules — and when those are broken, you want your own error messages. That’s where custom exceptions come in.
Defining your own exception class helps you raise meaningful, specific errors that are easier to debug and maintain. This tutorial walks you through everything you need to know — from syntax to output — about creating and using custom exceptions in Python.
To define a custom exception, we subclass the built-in Exception
class. Here's the basic syntax:
class MyCustomError(Exception):
pass
This creates a new exception type called MyCustomError
. Now, you can raise it using the raise
keyword.
raise MyCustomError("Something went wrong in your custom logic!")
Let’s say you’re writing a function that only accepts even numbers. If the input is odd, you want to raise your own error.
class NotEvenNumberError(Exception):
def __init__(self, number):
super().__init__(f"The number {number} is not even.")
def check_even(n):
if n % 2 != 0:
raise NotEvenNumberError(n)
return f"{n} is even."
# Test
print(check_even(10))
print(check_even(7))
10 is even.
Traceback (most recent call last):
...
NotEvenNumberError: The number 7 is not even.
You can go beyond basic text by passing arguments and overriding the __str__
method:
class LowBalanceError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
def __str__(self):
return f"Transaction failed: Balance (${self.balance}) is less than amount (${self.amount})."
def withdraw(balance, amount):
if amount > balance:
raise LowBalanceError(balance, amount)
return balance - amount
# Test
print(withdraw(100, 50))
print(withdraw(100, 150))
50
Traceback (most recent call last):
...
LowBalanceError: Transaction failed: Balance ($100) is less than amount ($150).
Exception
or a subclass of it — never from BaseException
unless you have a rare system-level reason.UserNotFoundError
or ConfigFileMissingError
.If you're building a large application, group related exceptions under a base class:
class AppError(Exception):
"""Base class for all application-specific errors."""
pass
class ConfigError(AppError):
pass
class DatabaseError(AppError):
pass
Use them when your application rules are broken. Examples:
ValueError
You can test them using try/except
blocks:
try:
withdraw(20, 50)
except LowBalanceError as e:
print("Caught:", e)
Caught: Transaction failed: Balance ($20) is less than amount ($50).
Custom exceptions give your code clarity and precision. Whether you’re building libraries, APIs, or full-stack apps, defining your own exceptions helps express intent and manage errors gracefully.
In the next lesson, we’ll explore how to handle both built-in and custom exceptions using try
, except
, and related keywords.
⬅ Previous Topic
Python Exception HandlingNext Topic ⮕
Python Object-Oriented ProgrammingYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.