0
0
Pythonprogramming~15 mins

Why custom exceptions are needed in Python - See It in Action

Choose your learning style9 modes available
Why Custom Exceptions Are Needed
📖 Scenario: Imagine you are building a simple banking app. You want to handle errors like trying to withdraw more money than the account has. Python has built-in errors, but sometimes you want to create your own special error messages that make it clear what went wrong in your app.
🎯 Goal: You will create a custom exception called InsufficientFundsError to show a clear message when someone tries to take out too much money from their bank account.
📋 What You'll Learn
Create a custom exception class called InsufficientFundsError that inherits from Exception.
Create a variable balance with the value 100.
Create a variable withdraw_amount with the value 150.
Write an if statement to check if withdraw_amount is greater than balance.
If it is, raise the InsufficientFundsError with the message 'Not enough money in your account.'.
If not, subtract withdraw_amount from balance.
Print the remaining balance.
💡 Why This Matters
🌍 Real World
Custom exceptions are used in real apps to give clear error messages that help users and developers understand problems quickly.
💼 Career
Knowing how to create and use custom exceptions is important for writing clean, maintainable code in software development jobs.
Progress0 / 4 steps
1
Create the custom exception class
Create a custom exception class called InsufficientFundsError that inherits from Exception.
Python
Need a hint?

Use class InsufficientFundsError(Exception): and inside write pass.

2
Set up the balance and withdraw amount
Create a variable called balance and set it to 100. Then create a variable called withdraw_amount and set it to 150.
Python
Need a hint?

Write balance = 100 and withdraw_amount = 150.

3
Check if withdrawal is possible and raise exception
Write an if statement to check if withdraw_amount is greater than balance. If it is, raise the InsufficientFundsError with the message 'Not enough money in your account.'. Otherwise, subtract withdraw_amount from balance.
Python
Need a hint?

Use if withdraw_amount > balance: then raise InsufficientFundsError('Not enough money in your account.'). Else subtract.

4
Print the remaining balance
Write print(balance) to display the remaining balance after the withdrawal check.
Python
Need a hint?

Just write print(balance). But since withdrawal is too big, the program will raise the custom error instead of printing.