try/except/else/finallyExceptions represent runtime errors that disrupt program execution. Python handles errors gracefully using try, except, else, and finally blocks, along with custom exception hierarchies.
flowchart TD
A["Enter try Block"] --> B{"Exception Raised?"}
B -- "Yes" --> C{"Matches except Clause?"}
C -- "Yes" --> D["Execute except Block"]
C -- "No" --> E["Propagate Upward"]
B -- "No" --> F["Execute else Block"]
D --> G["Execute finally Block"]
F --> G
G --> H["Continue Execution"]
try: Contains code that might trigger an exception.except ExceptionType as err: Catches and handles specific exception instances.else: Executes ONLY if NO exception was raised in the try block.finally: Executes ALWAYS (regardless of whether an exception occurred or was handled).class InsufficientFundsError(Exception):
"""Custom domain exception for account withdrawals."""
def __init__(self, balance: float, amount: float) -> None:
super().__init__(f"Cannot withdraw ${amount:.2f}; available balance is ${balance:.2f}.")
self.balance = balance
self.amount = amount
def process_withdrawal(balance: float, amount: float) -> float:
if amount > balance:
raise InsufficientFundsError(balance, amount)
return balance - amount
def safe_execution_wrapper() -> None:
current_balance = 100.0
try:
new_balance = process_withdrawal(current_balance, 150.0)
except InsufficientFundsError as err:
print(f"Caught Custom Exception: {err}")
except Exception as general_err:
print(f"Unexpected System Error: {general_err}")
else:
print(f"Withdrawal Successful! Remaining Balance: ${new_balance}")
finally:
print("Audit Log: Transaction attempt closed.")
if __name__ == "__main__":
safe_execution_wrapper()
except:: Catching bare except: traps system signals like KeyboardInterrupt and SystemExit, making scripts impossible to stop cleanly with Ctrl+C. Catch except Exception: instead.try Blocks Narrow: Wrap only the specific lines of code that can raise the anticipated exception inside the try block.raise NewException(...) from original_error to preserve original tracebacks.Write a function safe_divide(a: float, b: float) -> float | None that catches ZeroDivisionError and prints a warning instead of crashing.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.