Codectionary / Developer documentation / Python

try / except

The try/except block lets your program handle errors gracefully instead of crashing. Code that might raise an exception goes in the try block; if an exception occurs, execution jumps to the matching except block instead of stopping the program. You can catch specific exception types, provide a fallback with a generic except, run cleanup code with finally regardless of whether an error occurred, and even raise your own exceptions intentionally.

Syntax

try:\n    # risky code\nexcept ExceptionType as e:\n    # handle it

Examples

Basic Exception Handling

Catching an error instead of letting the program crash.

try:
    number = int("not a number")
except ValueError:
    print("That wasn't a valid number")

print("Program continues running")

Catching Specific Exceptions

Handling different error types differently by listing multiple except blocks.

def divide(a, b):
    try:
        result = a / b
        return result
    except ZeroDivisionError:
        print("Cannot divide by zero")
    except TypeError:
        print("Both arguments must be numbers")

divide(10, 0)      # Cannot divide by zero
divide(10, "two")  # Both arguments must be numbers

Using finally

Running cleanup code that always executes, whether or not an exception occurred.

def read_config():
    try:
        print("Reading configuration...")
        raise FileNotFoundError("config.json missing")
    except FileNotFoundError as e:
        print(f"Error: {e}")
    finally:
        print("Cleanup complete")  # always runs

read_config()

Raising Custom Exceptions

Intentionally raising an exception to signal an invalid state.

def withdraw(balance, amount):
    if amount > balance:
        raise ValueError("Insufficient funds")
    return balance - amount

try:
    new_balance = withdraw(100, 150)
except ValueError as e:
    print(f"Transaction failed: {e}")

Best practices

  • Catch specific exception types (ValueError, KeyError, etc.) rather than a bare except:, which can silently swallow unrelated bugs
  • Use finally for cleanup code (closing files, releasing resources) that must run regardless of success or failure
  • Raise exceptions with clear, descriptive messages to make debugging easier for whoever encounters the error
  • Don't use try/except for normal control flow when a simple if check would do - exceptions are for genuinely exceptional situations
  • Consider using the else clause on try blocks for code that should only run if no exception was raised

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading