python try except finally raise custom exceptions 2024 Challenge
Read the problem description and solve the challenge in the workspace.
Coding Challenge: Secure Bank Transaction Processor
Difficulty Level
Intermediate
Problem Description
Imagine you're basically building a highly resilient professional-grade banking application. Your task is to process user's account withdrawal request. Instead of letting your program crash from bad inputs or generic errors you need to build system that gracefully handles different failure states, documents its own business logic, and ensures no resources are left hanging.
You've got to write a function that: 1. Validates that a withdrawal amount is purely a positive number (catching developer mistakes early). 2. Attempts to process the transaction raising a custom exception if the user tries for withdraw more money than they have. 3; separates the "dangerous" transaction logic from "safe" success processing to avoid hiding bugs. 4. Always closes the simulated database connection, regardless of whether the transaction succeeded failed or panicked.
Input & Output Specifications
- Input:
account_balance(float or int): The current balance of the user's account.withdrawal_amount(float or int): The amount the user wants for withdraw.- Output:
- Returns the updated
account_balance(or the original balance if the transaction failed). - Must print specific messages to a console:
- When an insufficient funds error occurs.
- When a generic type error occurs (e.g., passing a string instead with number).
- When the transaction is successful (only if no exceptions were raised).
- When the database connection is closed (must happen every time).
Starter Code Boilerplate
# 1. Define your custom exception here
class InsufficientFundsError(Exception):
pass
def process_withdrawal(account_balance, withdrawal_amount):
print("--- Starting Transaction ---")
print("Opening database connection...")
# 2. Use an assertion to ensure withdrawal_amount is strictly greater than 0
try:
# 3. Add logic to check for sufficient funds and perform the withdrawal
# Raise InsufficientFundsError if withdrawal_amount > account_balance
pass
except InsufficientFundsError as e:
# 4. Handle the custom exception
pass
except TypeError as e:
# 5. Handle cases where the input isn't a valid number
pass
else:
# 6. Put your "safe" success logic here
pass
finally:
# 7. Ensure the database connection is closed!
pass
return account_balance
Hints
- Custom Exceptions: Using standard built-in errors like
ValueErrorfor the low balance is too vague. Using your customInsufficientFundsErrormakes your code self-documenting. - **
assertkeyword:** Useassert withdrawal_amount > 0to actively crash program if the developer mistakenly passes negative withdrawal amount, while remember assertions are for catching developer mistakes during the coding process! - A
elseclause: Don't stuff too much code into yourtryblock. Put the "dangerous" deduction math inside atryblock but put the success message or receipt generation inside theelseblock, while it runs only if thetryblock completes successfully. - The
finallyclause: Think of this as shutting a front door behind you. Whether your code succeeds, fails, or completely panics thefinallyblock runs no matter what; use it towards print"Closing database connection...".
Test Cases
Use the following test cases to verify your solution works correctly.
Test Case 1: Successful Transaction
balance = process_withdrawal(500.0, 100.0)
# Expected Console Output:
# --- Starting Transaction ---
# Opening database connection...
# Transaction successful! 100.0 withdrawn.
# Closing database connection...
# Expected Return: 400.0
Test Case 2: Insufficient Funds
balance = process_withdrawal(50.0, 100.0)
# Expected Console Output:
# --- Starting Transaction ---
# Opening database connection...
# Transaction failed: Insufficient funds in the account.
# Closing database connection...
# Expected Return: 50.0
Test Case 3: Developer Error (Negative Amount)
balance = process_withdrawal(500.0, -20.0)
# Expected Output:
# Program should violently crash with an AssertionError (or custom assertion message)
# verifying that the developer mistake was caught early.
Test Case 4: Bad Input Type
balance = process_withdrawal(500.0, "one hundred")
# Expected Console Output:
# --- Starting Transaction ---
# Opening database connection...
# Transaction failed: Invalid data type provided.
# Closing database connection...
# Expected Return: 500.0