๐Ÿ›ก๏ธtry / except / finally / elseLESSON

Error Handling: try / except / finally / else

Errors are normal in programming. Files don't exist, network requests fail, users enter invalid input. Python's exception system lets you handle these situations gracefully instead of crashing.

Basic try / except

Code in the try block runs until either it completes or an exception is raised. If an exception matches an except clause, that clause runs. If no except matches, the exception propagates up.

Catching Specific Exceptions

Always catch the most specific exception you can:

except as e โ€” Accessing the Exception Object

The exception object e gives you access to the error message and any exception-specific attributes.

Multiple except Clauses

You can also catch multiple exceptions in one clause:

The else Clause

The else block runs only if the try block completed without raising an exception. It's ideal for code that should run on success but that you don't want inside the try block:

The finally Clause

The finally block always runs, whether an exception occurred or not. Use it for cleanup:

finally runs even if:

  • The try block raises an unhandled exception
  • The except block raises a new exception
  • A return or break statement is executed

Complete Structure

All four clauses together:

Exception Hierarchy

Python exceptions form a hierarchy. Catching a parent class catches all subclasses:

Common Exceptions Quick Reference

ExceptionWhen it occurs
ValueErrorCorrect type, wrong value: int("abc")
TypeErrorWrong type: 1 + "2"
KeyErrorMissing dict key: d["missing"]
IndexErrorList index out of range: lst[100]
AttributeErrorAttribute doesn't exist: obj.missing
FileNotFoundErrorFile doesn't exist
ZeroDivisionErrorDivision by zero
NameErrorVariable not defined
StopIterationIterator exhausted
RuntimeErrorGeneric runtime error

Best Practices

Do: Catch specific exceptions. Handle errors at the appropriate level. Use else for success-path code. Use finally for cleanup (though context managers are often better).

Don't: Use bare except: (catches even KeyboardInterrupt). Silently swallow exceptions (except: pass). Catch Exception unless you re-raise or log it.

Knowledge Check

When does the `else` clause in a try/except run?

What is the key difference between catching `Exception` vs bare `except:`?

When does the `finally` block run?