0
0
Pythonprogramming~30 mins

Creating exception classes in Python - Try It Yourself

Choose your learning style9 modes available
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
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 add pass inside.

2
Set up 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?

Use simple assignment like balance = 100 and withdraw_amount = 150.

3
Write the withdraw function with exception
Write a function called withdraw that takes a parameter amount. Inside the function, if amount is greater than balance, raise InsufficientFundsError with the message 'Not enough money in the account'.
Python
Need a hint?

Use def withdraw(amount): and inside check if amount > balance: then raise InsufficientFundsError('Not enough money in the account').

4
Call withdraw and handle exception
Call the withdraw function with withdraw_amount inside a try block. Catch the InsufficientFundsError exception and print its message.
Python
Need a hint?

Use try: to call withdraw(withdraw_amount) and except InsufficientFundsError as e: to print e.