0
0
Pythonprogramming~30 mins

Extending built-in exceptions in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Extending built-in exceptions
📖 Scenario: Imagine you are building a simple banking app. You want to handle errors when someone tries to withdraw more money than they have.
🎯 Goal: Create a custom error by extending Python's built-in Exception class. Use it to show a clear message when a withdrawal is too large.
📋 What You'll Learn
Create a custom exception class called InsufficientFundsError that extends Exception
Add an __init__ method to InsufficientFundsError that takes balance and amount as parameters
Store balance and amount as attributes in InsufficientFundsError
Override the __str__ method to return a message like: 'Cannot withdraw {amount}, only {balance} available.'
Create a variable balance set to 100
Create a variable withdraw_amount set to 150
Write code that raises InsufficientFundsError if withdraw_amount is greater than balance
Use a try-except block to catch InsufficientFundsError and print the error message
💡 Why This Matters
🌍 Real World
Custom exceptions help make error messages clearer and easier to understand in real applications like banking or shopping apps.
💼 Career
Knowing how to extend exceptions is useful for writing clean, maintainable code and handling errors in professional software development.
Progress0 / 4 steps
1
Create the custom exception class
Create a class called InsufficientFundsError that extends Exception. Add an __init__ method that takes balance and amount as parameters and stores them as attributes.
Python
Need a hint?

Remember to use class InsufficientFundsError(Exception): to extend the built-in Exception class.

2
Add the __str__ method to show the error message
Add a __str__ method to InsufficientFundsError that returns the string: f"Cannot withdraw {self.amount}, only {self.balance} available."
Python
Need a hint?

The __str__ method should return a formatted string with self.amount and self.balance.

3
Set up balance and withdrawal amount variables
Create a variable called balance and set it to 100. Create another variable called withdraw_amount and set it to 150.
Python
Need a hint?

Use simple assignment to create balance and withdraw_amount.

4
Raise and catch the custom exception
Write a try-except block. Inside try, raise InsufficientFundsError(balance, withdraw_amount) if withdraw_amount is greater than balance. In except InsufficientFundsError as e, print e.
Python
Need a hint?

Use raise InsufficientFundsError(balance, withdraw_amount) inside the try block and catch it with except InsufficientFundsError as e.