0
0
Pythonprogramming~30 mins

Best practices for custom exceptions in Python - Mini Project: Build & Apply

Choose your learning style9 modes available
Best practices for custom exceptions
📖 Scenario: Imagine you are building a simple banking application. You want to handle errors clearly when users try to withdraw more money than they have in their account.
🎯 Goal: Create a custom exception called InsufficientFundsError to handle withdrawal errors. Use it in a function that withdraws money from an account balance.
📋 What You'll Learn
Create a custom exception class named InsufficientFundsError that inherits from Exception.
Add a constructor to InsufficientFundsError that accepts a message and passes it to the base class.
Create a variable balance with the value 100.
Create a function withdraw(amount) that raises InsufficientFundsError if amount is greater than balance.
Use a try-except block to call withdraw(150) and print the error message if caught.
💡 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
Understanding custom exceptions is important for writing robust, 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. Add an __init__ method that takes a message parameter and passes it to super().__init__(message).
Python
Need a hint?

Remember to inherit from Exception and call super().__init__(message) inside the constructor.

2
Create the balance variable
Create a variable called balance and set it to 100.
Python
Need a hint?

Just create a variable named balance and assign it the value 100.

3
Create the withdraw function with exception
Create a function called withdraw that takes a parameter amount. Inside the function, check if amount is greater than balance. If yes, raise InsufficientFundsError with the message "Not enough funds to withdraw {amount}". Otherwise, subtract amount from balance.
Python
Need a hint?

Use raise InsufficientFundsError(...) to throw the error when amount is too big.

4
Use try-except to handle the exception
Write a try-except block that calls withdraw(150). Catch the InsufficientFundsError as e and print e.
Python
Need a hint?

Use try to call withdraw(150) and except InsufficientFundsError as e to catch and print the error.