Creating exception classes
📖 Scenario: Imagine you are building a simple banking system. You want to handle errors like when someone tries to withdraw more money than they have.
🎯 Goal: You will create a custom exception class called InsufficientFundsError to handle this specific error. Then you will use it in a function that withdraws money from an account.
📋 What You'll Learn
Create a custom exception class named
InsufficientFundsError that inherits from Exception.Create a variable
balance with the value 100.Create a variable
withdraw_amount with the value 150.Write a function
withdraw that takes amount as a parameter.Inside the function, raise
InsufficientFundsError with the message 'Not enough money in the account' if amount is greater than balance.Call the
withdraw function with withdraw_amount inside a try block.Catch the
InsufficientFundsError exception and print its message.💡 Why This Matters
🌍 Real World
Custom exceptions help you handle specific errors in your programs clearly, like when a bank account has insufficient funds.
💼 Career
Knowing how to create and use custom exceptions is important for writing robust software that handles errors gracefully in real-world applications.
Progress0 / 4 steps