Python:Python Exception Handling: try, except, else, and finally
Python•Error Handling

Python Exception Handling: try, except, else, and finally

Robust code anticipates potential failures (ZeroDivisionError, ValueError, KeyError) and handles them cleanly with try, except, else, and finally.

Syntax

try: # risky operations except SpecificError as e: # error handler else: # runs only if no error occurred finally: # always executes

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
tryBlockCode being monitored for exceptions.
except SpecificErrorHandlerCatches matching exception types.
finallyCleanup BlockRuns unconditionally regardless of errors.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Python locally:

# Robust Safe Division Function
def safe_divide(numerator: float, denominator: float):
    print(f"\nDividing {numerator} by {denominator}:")
    try:
        result = numerator / denominator
    except ZeroDivisionError:
        print("  Error: Cannot divide by zero!")
        return None
    except TypeError as err:
        print(f"  Error: Invalid numeric types: {err}")
        return None
    else:
        print(f"  Success: Result = {result:.2f}")
        return result
    finally:
        print("  [Cleanup] Calculation attempt finished.")

safe_divide(100, 4)
safe_divide(50, 0)
Expected Output:
Dividing 100 by 4:
  Success: Result = 25.00
  [Cleanup] Calculation attempt finished.

Dividing 50 by 0:
  Error: Cannot divide by zero!
  [Cleanup] Calculation attempt finished.

How It Works: Step-by-Step

  • Lines 4-5: Attempts division inside the protected try block.
  • Lines 6-11: Catches ZeroDivisionError and TypeError explicitly.
  • Lines 12-14: else executes only when the try block completes without raising.
  • Lines 15-16: finally executes unconditionally for clean resource release.

Key Concepts

  • Catch specific exceptions instead of a bare except: to avoid swallowing unexpected errors.
  • else: runs only when the try block executes without any raised exceptions.
  • finally: always runs, even if an unhandled exception or return statement occurs.

Common Mistake: Using a bare except: clause without specifying exception types

A bare except catches SystemExit and KeyboardInterrupt, making programs impossible to terminate normally.

❌ Incorrect
try:
    do_task()
except: # Catches even Ctrl+C and exit signals!
    pass
✅ Correct
try:
    do_task()
except Exception as e: # Catches standard runtime errors
    print(f"Task failed: {e}")

Related Python Tutorials & Compiler

Run and test Python on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Python Online Compiler