01 / 22
!

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.

Python

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.

ZeroDivisionError
Dividing a number by zero
ValueError
Function gets an argument with the right type but an invalid value
FileNotFoundError
Trying to open a file that does not exist

Why Handle Errors?

1
Prevent crashes. Your program keeps running even when unexpected input arrives.
2
User-friendly messages. Instead of a scary traceback, you show a helpful message.
3
Resource cleanup. Close files, network connections, and database handles reliably.
4
Debugging info. Log exceptions to help you find and fix bugs faster.

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.

try
Code that might raise an exception
except
Runs only if an exception occurs
else
Runs only if no exception occurs
finally
Runs always, no matter what

Execution Flow Diagram

try Error? except Yes else No finally Done Always runs

The Complete Syntax

try: # Code that might fail risky_operation() except SomeError as e: # Handle the specific error print(f"Error: {e}") else: # Runs only if NO exception was raised print("Success!") finally: # ALWAYS runs, error or not cleanup()

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

1
Identify the risky code. What operation could fail? Put only that code inside try.
2
Catch specific exceptions. Write an except for each error type you anticipate.
3
Add success logic to else. If the try block succeeds, run your next step in else.
4
Clean up in finally. Close files, release locks, or log results in finally.
5
Test both paths. Run your code with valid input AND invalid input to verify both branches.

Example 1: Safe Division

def safe_divide(a, b): try: result = a / b except ZeroDivisionError: print("Cannot divide by zero!") return None else: print(f"Result: {result}") return result finally: print("Division attempted.")
safe_divide(10, 2)
Prints "Result: 5.0" then "Division attempted."
safe_divide(10, 0)
Prints "Cannot divide by zero!" then "Division attempted."

Example 2: File Reading

f = None try: f = open("data.txt", "r") content = f.read() except FileNotFoundError: print("File not found!") except PermissionError: print("No permission to read!") else: print(f"Read {len(content)} chars") finally: if f: f.close() print("File closed.")

Example 3: User Input Validation

def get_age(): try: age = int(input("Enter age: ")) if age < 0: raise ValueError("Negative age") except ValueError as e: print(f"Invalid: {e}") return None else: print(f"Age accepted: {age}") return age

Catching Multiple Exceptions

Python offers two ways to handle multiple exception types:

Separate blocks
Use multiple except clauses for different handling per error type
Tuple syntax
Use except (TypeA, TypeB) to handle several errors the same way
# Separate handlers except ValueError: print("Bad value") except TypeError: print("Wrong type") # Grouped handler except (ValueError, TypeError) as e: print(f"Input error: {e}")

Python's Exception Hierarchy

BaseException Exception ValueError TypeError OSError FileNotFoundError UnicodeError Catching a parent class catches all its children

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:

Inside try
Extra code in try could raise an exception that gets accidentally caught by your except
Inside else
Code in else is not protected by except, so new errors propagate correctly

finally Always Runs

The finally block executes in every scenario, even when you might not expect it:

1
After the try block succeeds normally
2
After an except block handles an error
3
Even if return is called inside try, except, or else
4
Even if an unhandled exception is about to crash the program

Common Mistakes

✕ Bare except
Writing except: with no error type catches everything, hiding bugs you should fix.
✕ Too much in try
Wrapping 20 lines in try makes it unclear which line might fail and masks unrelated errors.
✕ Silencing errors
Using except: pass swallows errors silently. At minimum, log what happened.

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

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

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?