We're making some improvements. Some features may be temporarily unavailable.
intermediate25 min

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:

ExceptionWhen It Happens
ValueErrorWrong value (e.g., int("hello"))
TypeErrorWrong type (e.g., "hello" + 5)
ZeroDivisionErrorDivision by zero
IndexErrorList index out of range
KeyErrorDictionary key not found
FileNotFoundErrorFile doesn't exist
AttributeErrorObject has no such attribute

Common Exceptions (Don't Run These Raw!)

Output
Run your code to see output here

Basic try/except

The try block contains code that might fail. The except block runs if an exception occurs:

Basic try/except

Output
Run your code to see output here

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

Output
Run your code to see output here

The else and finally Clauses

  • else runs if no exception occurred
  • finally ALWAYS runs — whether an exception happened or not

Using else and finally

Output
Run your code to see output here

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

Output
Run your code to see output here

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.

Python will load on first run

Best Practices

  1. Be specific — catch specific exceptions, not bare except:
  2. Don't swallow errors silently — at minimum, log them
  3. Use finally for cleanup — files, connections, locks
  4. Raise meaningful errors — clear messages help debugging
  5. Handle errors at the right level — close to where they can be resolved

Key Takeaways

  • try/except prevents crashes and allows graceful error handling
  • Catch specific exceptions to handle different problems differently
  • else runs on success, finally always runs (perfect for cleanup)
  • raise lets you create your own exceptions
  • Error handling is what separates scripts from professional software

Questions & Discussion

Sign in to ask a question or join the discussion.

Loading comments...