Custom Exception Classes
Define your own exception types for clearer error communication.
Custom Exception Classes is a free Python Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Introduction
Why Custom Exceptions?
class AppError(Exception):
pass
raise AppError('something went wrong')Inheriting from Exception
class ValidationError(Exception):
pass
try:
raise ValidationError('email is invalid')
except ValidationError as e:
print(e)Adding Custom Attributes
class APIError(Exception):
def __init__(self, status, message):
self.status = status
super().__init__(message)
try:
raise APIError(404, 'Not found')
except APIError as e:
print(e.status, e)Exception Hierarchy
class AppError(Exception): pass
class DBError(AppError): pass
class NetworkError(AppError): pass
try:
raise DBError('timeout')
except AppError as e:
print('app error:', e)Custom __str__ Method
class RangeError(ValueError):
def __init__(self, val, lo, hi):
self.val, self.lo, self.hi = val, lo, hi
def __str__(self):
return f'{self.val} not in [{self.lo}, {self.hi}]'
print(RangeError(15, 0, 10))Raising Custom Exceptions
class InsufficientFundsError(Exception):
def __init__(self, needed, available):
super().__init__(f'Need {needed}, have {available}')
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(amount, balance)
return balance - amount
try:
withdraw(100, 200)
except InsufficientFundsError as e:
print(e)Catching by Base Class
class AppError(Exception): pass
class DBError(AppError): pass
try:
raise DBError('conn failed')
except AppError:
print('any app error')Exception with Context Manager
class SuppressValue(Exception): pass
try:
raise SuppressValue('ignored')
except SuppressValue:
pass # suppress silently
print('continued')Documenting Custom Exceptions
class ConfigError(Exception):
"""Raised when configuration is invalid.
Attributes:
key: The invalid config key
"""
def __init__(self, key, msg):
super().__init__(msg)
self.key = keyBest Practices
# Good structure:
class AppError(Exception): pass
class ValidationError(AppError): pass
class NotFoundError(AppError): pass
print('hierarchy demo')Quick Check
Recap
Keep Going
Frequently asked questions
Is the “Custom Exception Classes” lesson free?
Yes — the full text of “Custom Exception Classes” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.
What will I learn in “Custom Exception Classes”?
Define your own exception types for clearer error communication. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Python Academy?
No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Custom Exception Classes” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Python Academy lesson?
Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Understanding Exceptions
- try / except / else / finally
- Raising and Re-raising Exceptions
- Custom Exception Classes