Error Handling
Handle errors gracefully with try/except
Why Handle Errors?
Every program encounters errors. Without error handling, your program crashes and users see scary tracebacks. With error handling, your program responds gracefully — showing a helpful message, trying again, or logging the issue.
Common Python Exceptions
Python has many built-in exception types. Here are the most common:
| Exception | When It Happens |
|---|---|
ValueError | Wrong value (e.g., int("hello")) |
TypeError | Wrong type (e.g., "hello" + 5) |
ZeroDivisionError | Division by zero |
IndexError | List index out of range |
KeyError | Dictionary key not found |
FileNotFoundError | File doesn't exist |
AttributeError | Object has no such attribute |
Common Exceptions (Don't Run These Raw!)
Basic try/except
The try block contains code that might fail. The except block runs if an exception occurs:
Basic try/except
Check Your Understanding
What happens if you DON'T use try/except and an error occurs?
Catching Multiple Exceptions
You can handle different exceptions differently:
Multiple except Blocks
The else and finally Clauses
elseruns if no exception occurredfinallyALWAYS runs — whether an exception happened or not
Using else and finally
Check Your Understanding
When does a `finally` block execute?
Raising Your Own Exceptions
Use raise to signal that something went wrong in your own code:
Raising Exceptions
Exercise
Write a `safe_average()` function that takes a list of numbers. It should handle: (1) Empty lists (raise a ValueError), (2) Non-numeric items in the list (skip them with a warning), and (3) Return the average. Use try/except inside a loop to handle non-numeric items.
Best Practices
- Be specific — catch specific exceptions, not bare
except: - Don't swallow errors silently — at minimum, log them
- Use finally for cleanup — files, connections, locks
- Raise meaningful errors — clear messages help debugging
- Handle errors at the right level — close to where they can be resolved
Key Takeaways
try/exceptprevents crashes and allows graceful error handling- Catch specific exceptions to handle different problems differently
elseruns on success,finallyalways runs (perfect for cleanup)raiselets you create your own exceptions- Error handling is what separates scripts from professional software