Skip to content
AgileLogics
5 min read

Exceptions

Prerequisites: Basic error handling

Beyond catching built-in exceptions, you can define and raise your own to signal a specific problem clearly.

class InsufficientFundsError(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError("Not enough balance")
    return balance - amount

try:
    withdraw(100, 150)
except InsufficientFundsError as error:
    print(f"Withdrawal failed: {error}")
finally:
    print("Transaction attempt finished")

Expected output

Withdrawal failed: Not enough balance
Transaction attempt finished

finally runs whether or not an exception happened — useful for cleanup (closing a file, a network connection) that must always occur.