# Exception Handling: try, except, else, finally

> Master robust Python error handling: catching specific exceptions, executing clean code in else blocks, guaranteeing cleanup with finally, raising custom exceptions, and avoiding the dangerous bare except antipattern.

Subject: Python | Lesson 21 of 24 | 7 min read
Interactive lesson: https://codewithanimation.in/python/exceptions
Previous: [JSON Serialization & Parsing (dumps, loads)](https://codewithanimation.in/python/json.md) | Next: [Comprehensions: List, Dict & Set Expressions](https://codewithanimation.in/python/list-comprehensions.md)

## The Four Chambers: try, except, else, finally

In Python, errors during runtime trigger exceptions. Rather than crashing the entire process, Python provides a structured four-part construct to handle failures gracefully: `try`, `except`, `else`, and `finally`.

The `try` block wraps code that might raise an error. If an exception occurs, Python halts execution in `try` and jumps immediately to the matching `except` block.

If no exception occurs, the optional `else` block runs. Finally, the `finally` block executes unconditionally at the end of the lifecycle, regardless of whether exceptions were caught, unhandled, or triggered an early return.

## Why the else Block Matters

Many developers overlook the `else` clause in exception handling, placing code that follows the risky operation directly inside the `try` block. This is bad practice.

If you put non-risky code inside `try`, any incidental exception it raises might accidentally match your `except` clause, masking unintended bugs.

The `else` block executes only when the `try` block completes successfully without raising an error. This separates risky statements (like network calls or JSON parsing) from the downstream business logic that acts on the successful result.

## Catching Specific Exceptions and Chaining with raise from

Always catch specific exceptions (for example `except ValueError:`, `except KeyError:`, or `except (TypeError, ZeroDivisionError):`). This ensures your program handles only the specific failures you anticipated.

To inspect the exception message, bind it to a variable using `except ValueError as err:`.

When re-raising an exception or transforming a low-level error into a domain exception, use `raise CustomError('User not found') from err`. The `from` clause preserves the original root-cause traceback, making production debugging straightforward.

## Common mistake: The Silent Killer: Bare except and except Exception

The most dangerous antipattern in Python is a bare `except:` clause (or `except Exception: pass`). This swallows all errors silently, including typos, missing imports, memory errors, and system signals like `KeyboardInterrupt` (`Ctrl+C`).

Swallowed exceptions make applications impossible to debug because the failure vanishes without a traceback or log entry.

Always catch the most specific exception possible, and at minimum log the error message using Python's `logging` module rather than discarding it with `pass`.

## Tip: Create Domain-Specific Custom Exceptions

Define custom exception classes by subclassing `Exception` (never `BaseException`): `class InsufficientFundsError(Exception): pass`. This allows callers of your library or API to catch your exact application errors specifically without catching unrelated runtime errors.

## Try it: The Exception Execution Pipeline Chamber

Feed different inputs into a division pipeline: a valid number, a zero divisor, and an invalid string. Watch the active chamber illuminate step-by-step, proving that else runs only on success, while finally runs unconditionally every time.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/python/exceptions

## Check yourself

### Question 1

Under what condition does the `else` block execute in a `try ... except ... else ... finally` statement?

- A. Only when the try block completes successfully without raising any exceptions
- B. Whenever an except block catches and resolves an error
- C. Unconditionally on every execution like finally
- D. Only if the finally block returns a falsy value

Correct answer: A

The `else` block runs if and only if the `try` block finishes without raising any exception.

- Why not B: If an exception is raised, the except block runs and the else block is skipped.
- Why not C: finally is unconditional; else is conditional upon zero exceptions.
- Why not D: The else block executes before finally.

### Question 2

What will happen if you include `return 1` in `try` and `return 2` in `finally`?

- A. The function returns 2 because finally overrides previous return values
- B. The function returns 1 and ignores finally
- C. Python raises a SyntaxError during compilation
- D. The function returns a tuple (1, 2)

Correct answer: A

The `finally` clause executes before leaving the `try` statement. If `finally` executes a `return` or `break`, that return value overrides any pending return value from `try`.

- Why not B: The finally block always runs before the function exits and supersedes pending return values.
- Why not C: Return in finally is valid syntax, though discouraged due to confusing behavior.
- Why not D: Only a single return value is emitted.

### Question 3

Why is catching a bare `except:` considered a dangerous antipattern?

- A. It catches BaseException, swallowing KeyboardInterrupt (Ctrl+C) and system exit signals
- B. It slows down Python execution by 500%
- C. It forces Python to restart the operating system
- D. Python 3 raises a DeprecationWarning on bare except

Correct answer: A

A bare `except:` catches `BaseException`, intercepting `SystemExit`, `KeyboardInterrupt`, and internal interpreter signals, preventing users from stopping running programs with `Ctrl+C`.

- Why not B: Exception handling has negligible overhead when exceptions are not raised.
- Why not C: Bare except does not restart the operating system.
- Why not D: Bare except is legal syntax, but considered bad practice.

## Remember this

- The try block holds risky operations; except catches and handles specific error types.
- The else block runs only if the try block completes successfully with zero exceptions.
- The finally block runs unconditionally every time, even if an exception is unhandled.
- Never write a bare except: pass; it swallows syntax errors and system signals.
- Chain related exceptions using raise NewError() from original_err to preserve stack traces.
