The Full Handler: try-except-else-finally
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Python offers a comprehensive 4-part exception handling structure. The else block runs when no exception occurs, and the finally block is guaranteed to run no matter what.
The else block: running on success
Else clause is a block after the except blocks that runs only when the try block finished without an error.
The else block executes only if the try block completed with zero exceptions.
try: num = int("42")except ValueError: print("Conversion error")else: print(f"Success! Parsed number: {num}")Example 1 · Using else after a good conversion
text = "250"
try: amount = int(text)except ValueError: print("Invalid amount")else: print(f"Amount accepted: {amount}")Amount accepted: 250
What this code does
- The
tryholds only the risky line,int(text). - It succeeds, so
exceptis skipped andelseruns.
Keeping code that depends on the try block succeeding inside else avoids accidentally catching exceptions from subsequent statements.
The finally block: guaranteed cleanup
Finally clause is a block that runs every time, whether the try block succeeded, failed or returned. It is used for clean-up.
The finally block always executes, regardless of whether an exception occurred, was caught, or was re-raised.
try: print("Opening connection") res = 10 / 2except ZeroDivisionError: print("Math error")finally: print("Closing connection")Example 2 · finally runs even with a return
def read_stock(stock, item): try: return stock[item] except KeyError: return 0 finally: print(f"Checked {item}")
stock = {"pen": 40}print(read_stock(stock, "pen"))print(read_stock(stock, "bag"))Checked pen 40 Checked bag 0
What this code does
returninsidetryorexceptwaits untilfinallyhas run.Checked ...prints for both calls, found or not.- The second call returns 0 from
exceptafter thefinallyblock.
Even if the try block hit a return or raised an error, finally executes before control leaves the scope.
The complete execution flow
Try statement is the full structure of try, except, else and finally. Each part has one job: run, recover, continue or clean up.
The 4 parts work together with a clear lifecycle:
Example 3 · A bank transfer with all four parts
def transfer_funds(amount): print("Begin transaction") try: if amount <= 0: raise ValueError("Amount must be positive") balance = 500 - amount except ValueError as err: print(f"Transaction failed: {err}") else: print(f"Transfer successful. New balance: {balance}") finally: print("Transaction session closed")
transfer_funds(150)Begin transaction Transfer successful. New balance: 350 Transaction session closed
What this code does
- Runs try block with valid positive amount (150).
- Executes else block because no exception occurred.
- Executes finally block unconditionally to close session.
try: runs the guarded code. except: runs only if a matching exception occurs in try.
else: runs only if try completed without any exceptions. finally: runs always, unconditionally, before exiting.
Next step
Check your understanding
8 quick questions