Remember
A custom exception is a class derived from Exception. Raise it when your program needs to signal a specific failure.
A custom exception is a class derived from Exception. Raise it when your program needs to signal a specific failure.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
class InvalidScore(Exception):
pass
score = 3
try:
if score < 0:
raise InvalidScore("Score must be non-negative")
print(score)
except InvalidScore as error:
print(str(error))Top-level scope
class InvalidScoreObject 2 · int3A custom exception is a class derived from Exception. Raise it when your program needs to signal a specific failure.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
class InvalidScore(Exception):
pass
score = 3
try:
if score < 0:
raise InvalidScore("Score must be non-negative")
print(score)
except InvalidScore as error:
print(str(error))
|
v
DISPLAYED RESULT
3
FINAL BINDINGS
InvalidScore --> object 1 (type)
score --> object 2 (int)
object 1: class InvalidScore
object 2: 3Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
class InvalidScore(Exception):
pass
score = 3
try:
if score < 0:
raise InvalidScore("Score must be non-negative")
print(score)
except InvalidScore as error:
print(str(error))Top-level scope
class InvalidScoreObject 2 · int3The example has finished. Compare the final output with the values and references above.
3
What do you expect this program to print?
class InvalidScore(Exception):
pass
score = 3
try:
if score < 0:
raise InvalidScore("Score must be non-negative")
print(score)
except InvalidScore as error:
print(str(error))In 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:
ValueErrorYou can test them using try/except blocks:
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
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.
Connect what you noticed in the example with the idea below.
A custom exception is a class derived from Exception. Raise it when your program needs to signal a specific failure.
A custom exception must inherit from int.
This is the misconception to avoid.Reaching the recap and completing the quizzes are separate milestones.