Try / Except / Else / Finally
Python Error Handling
Master Python's four-block error handling structure to write robust, crash-proof programs that handle the unexpected gracefully.
What Are Runtime Errors?
When Python encounters something it cannot handle during execution, it raises an exception: an object that describes what went wrong. Without handling, the exception crashes your program instantly.
Why Handle Errors?
The Four Blocks at a Glance
Python's error handling uses four keywords that work together. Each block has a distinct role in the flow.
Execution Flow Diagram
The Complete Syntax
else vs. finally
Students often confuse these two blocks. The key difference is when they execute:
| else | finally | |
|---|---|---|
| Runs on success? | ✓ Yes | ✓ Yes |
| Runs on error? | ✕ No | ✓ Yes |
| Common use | Continue processing | Cleanup resources |
| Required? | Optional | Optional |
How to Apply This Pattern
Example 1: Safe Division
Example 2: File Reading
Example 3: User Input Validation
Catching Multiple Exceptions
Python offers two ways to handle multiple exception types:
Python's Exception Hierarchy
Why else Matters
You might ask: "Can't I just put success code at the end of the try block?" Technically yes, but there's an important difference:
finally Always Runs
The finally block executes in every scenario, even when you might not expect it:
Common Mistakes
Summary Table
| Block | When It Runs | Common Use | Required? |
|---|---|---|---|
| try | Always (first) | Risky operation | Yes |
| except | Only on error | Handle / log error | Need except or finally |
| else | Only on success | Continue processing | Optional |
| finally | Always (last) | Cleanup resources | Optional |
Question 1 of 5
Which block runs only when no exception is raised in the try block?
Question 2 of 5
Consider this code:
try:
x = int("hello")
except ValueError:
print("A")
else:
print("B")
finally:
print("C")
What is printed when this code runs?
Question 3 of 5
Why is writing except: with no exception type considered bad practice?
Question 4 of 5
Consider this code:
def test():
try:
return 1
finally:
return 2
What does test() return?
Question 5 of 5
What is the best reason to put success logic in else instead of at the end of the try block?