Learn Python
>>> exception_handling.custom_exceptions

Custom Exceptions in Python

#concept

A custom exception is a new exception type defined for a specific program, created by subclassing Python's built-in Exception class (or a more specific existing exception). It lets code raise and catch errors that are meaningful to a particular application's domain, rather than making do with only generic built-in types.

#how it works
1

Subclass Exception

Or a more specific, suitable built-in exception, whichever fits better.

2

A plain pass body is usually enough

Inheriting Exception's behavior covers most needs without extra code.

3

Add a custom __init__() if needed

For an exception that needs to carry extra data beyond a simple message.

4

Raise it like any built-in exception

raise MyCustomError("message") works exactly the same way.

5

Catch it the same way too

except MyCustomError as e behaves identically to catching a built-in type.

#example
class InsufficientFundsError(Exception):
pass
 
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(f"Cannot withdraw {amount}, balance is {balance}")
return balance - amount
 
try:
withdraw(100, 150)
except InsufficientFundsError as e:
print(f"Transaction failed: {e}")
Output
Transaction failed: Cannot withdraw 150, balance is 100
1class InsufficientFundsError(Exception): defines a new exception type specific to this program's domain.
2withdraw(100, 150) checks the condition and raises the custom exception, with a descriptive message built right in.
3except InsufficientFundsError as e catches it exactly like a built-in exception would be caught, and prints the specific message that was raised.
#use cases
Representing domain-specific failures clearly, like InsufficientFundsError or InvalidOrderError, instead of a generic ValueError
Letting calling code catch a program's own exceptions specifically, without accidentally catching unrelated built-in errors too
Building a small hierarchy of related custom exceptions, all inheriting from one common base exception for that application
Making error handling self-documenting, since the exception’s name itself explains what went wrong

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.