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 ExceptionAdd an
__init__ method to InsufficientFundsError that takes balance and amount as parametersStore
balance and amount as attributes in InsufficientFundsErrorOverride the
__str__ method to return a message like: 'Cannot withdraw {amount}, only {balance} available.'Create a variable
balance set to 100Create a variable
withdraw_amount set to 150Write code that raises
InsufficientFundsError if withdraw_amount is greater than balanceUse 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