Learning navigation

Code with Animation

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.

Python7 min readConcept 21 of 24

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.

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.

Select Input Scenario:
# 1. Risky operation:
try:
res = a / b
# 2. Specific handlers:
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid number!")
# 3. Runs only on success:
else:
print(f"Success: {res}")
# 4. Unconditional cleanup:
finally:
print("Cleanup completed")
EXCEPTION EXECUTION PIPELINE CHAMBER1. TRYAlways EntersExecution:10 / 2 ➔ 5.0 (Clean)2. EXCEPTSkippedHandler Status:No exception raised3. ELSESuccess OnlyDownstream Logic:Prints 'Success: 5.0'4. FINALLYGuaranteedResource Cleanup:Runs unconditionallyCLEAN PATH: try ➔ else runs on success ➔ finally runs unconditionally✓ else isolates success logic from risky try block
★ Python Rule: Never write a bare except: pass. A bare except catches BaseException, swallowing keyboard interrupts (Ctrl+C) and silencing critical bugs. Always catch specific exceptions.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Under what condition does the `else` block execute in a `try ... except ... else ... finally` statement?
  2. 2What will happen if you include `return 1` in `try` and `return 2` in `finally`?
  3. 3Why is catching a bare `except:` considered a dangerous antipattern?

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.

Done with this concept?

Mark it complete to track your progress. No login needed.