Python Exception Handling (try / except)
In the real world, things go wrong: users type words when you asked for numbers, servers drop connections, or files go missing. Without error handling, your program crashes with an ugly traceback. With try / except, your code catches errors and recovers gracefully.
"try/except is the digital safety net under a tightrope walker. If the program slips (an error occurs), the safety net catches it, dusts it off, and allows the show to go on without crashing into the ground."
Deep Dive: How It Works
The try block contains risky code that might cause an exception (like converting user input with int() or dividing by a variable).
The except block only executes if an error occurs inside the try block. You can catch specific error types (e.g. except ValueError:, except ZeroDivisionError:).
The else block (optional) runs only if NO error occurred in the try block.
The finally block (optional) ALWAYS runs no matter what (even if an error occurred), which is great for closing open files or database connections.
Syntax Blueprint
try:
number = int(user_input)
result = 100 / number
except ValueError:
print("Please enter digits only!")
except ZeroDivisionError:
print("Cannot divide by zero!")Wrap risky code in try, and handle specific error types in except blocks.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Using a bare except: with no error typeWhy it happens: A bare except catches everything, including KeyboardInterrupt (Ctrl+C), making your script impossible to cancel.
How to fix: Catch specific errors: except ValueError: or except Exception as e:.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Catch a ZeroDivisionError
Wrap 10 / 0 inside a try block.
In the except ZeroDivisionError: block, print "Cannot divide by zero".
Finished reading and practicing?
Mark this lesson as completed to update your course progress.