The try and except Blocks
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Wrap code that might fail inside a try block. If an error occurs, Python jumps immediately to the matching except block, allowing your program to recover gracefully.
Basic try-except block
Exception handling is writing code that catches an error and responds to it, so the program keeps running instead of crashing.
Place potentially failing statements in try:. If an exception occurs, the except: block executes instead of crashing.
try: number = int("abc")except ValueError: print("Conversion failed: not a valid integer")Example 1 · Reading a quantity
quantity_text = "three"
try: quantity = int(quantity_text) print(f"Ordered {quantity} items")except ValueError: print("Quantity must be a whole number")Quantity must be a whole number
What this code does
int("three")raisesValueError, so theprintinsidetryis skipped.- Python jumps to the matching
exceptand prints the message. - The program then continues normally.
Because 'abc' is invalid, execution skips the rest of the try block and prints the friendly recovery message.
Capturing error details with as err
Exception object is the value Python creates when an error happens. Writing except ... as err gives it a name so you can print its message.
Capture the exception instance using as variable_name to inspect the error message.
try: res = 10 / 0except ZeroDivisionError as err: print(f"Caught error: {err}")Example 2 · Reading the error message
stock = {"pen": 40, "book": 12}
try: print(stock["bag"])except KeyError as err: print(f"No such product: {err}")No such product: 'bag'
What this code does
stock["bag"]raisesKeyErrorbecause there is no such key.as errstores the exception object, and printing it shows the missing key.
The console displays Caught error: division by zero. You can log err to telemetry or monitoring services.
Handling multiple distinct exceptions
Multiple except blocks are a chain of except clauses on one try. Python checks them from top to bottom and runs the first one that matches.
Attach multiple except blocks to handle different failure modes distinctly.
def process_data(items, index): try: val = int(items[index]) return 100 // val except IndexError: return "Error: Index out of range" except ValueError: return "Error: Non-numeric data" except ZeroDivisionError: return "Error: Cannot divide by zero"Example 3 · Dividing safely
user_input = "100"try: val = int(user_input) result = 500 // val print(f"Result: {result}")except (ValueError, ZeroDivisionError) as err: print(f"Calculation error: {err}")Result: 5
What this code does
- Attempts to parse input and divide 500 by value.
- Executes successfully, printing 'Result: 5'.
Python checks each except block from top to bottom, executing only the first matching handler.
Where an uncaught error goes
Call stack is the list of function calls that are active right now. An unhandled error moves up this list until some function has a matching except.
A function does not need its own try. If it has none, the error moves up to the function that called it.
def parse_price(text): return float(text)
def load_row(row): return parse_price(row)
try: load_row("abc")except ValueError: print("Bad price")The error stops at the first function that has a matching except.
The error starts in parse_price, passes through load_row, and is caught in the top-level try.
Next step
Check your understanding
8 quick questions