Python Tutorial / Handle Exceptions with try, except, else, finally and raise

Exception handling distinguishes expected failures that can be recovered from or reported to a caller. Keep try blocks focused and catch only failures you can handle so that unrelated defects remain visible.

Understand the execution paths

An exception inside try transfers control to a matching except handler. else runs when try finishes without an exception; finally provides cleanup across normal and exceptional exits. A return inside finally can suppress a pending exception or return value and is usually inappropriate.

Use raise to signal a violated rule explicitly. An input error that a user can correct differs from a storage failure that must be reported to a higher layer.

For the relevant APIs and platform requirements, see Python: errors.

Failure logging and guaranteed cleanup build on the rules demonstrated in Understand Decorators and Context Managers.

Run normal and invalid amount cases

Save the complete code below as exceptions_demo.py in a separate practice folder, using UTF-8. Run python exceptions_demo.py in a terminal with your project virtual environment selected. Outside a virtual environment on macOS or Ubuntu, use python3 when that is your interpreter command.

def parse_amount(text):
    amount = int(text)
    if amount < 0:
        raise ValueError("amount must be nonnegative")
    return amount

for text in ["8000", "abc", "-1"]:
    try:
        amount = parse_amount(text)
    except ValueError as error:
        print("invalid:", text)
    else:
        print("accepted:", amount)
    finally:
        print("checked")

Expected output:

accepted: 8000
checked
invalid: abc
checked
invalid: -1
checked

Handle the cause at the right boundary

Integer parsing can raise ValueError; file access can raise FileNotFoundError or PermissionError. except Exception: pass hides failures and may let later operations continue with invalid state. For unexpected errors, add useful context and re-raise instead of silently proceeding.

Use context managers such as with for resources when possible. Manual finally cleanup must account for resources that failed to initialize. To expose a higher-level exception while preserving its cause, use raise NewError(...) from error.

Catching an exception and returning lets the caller continue with that value. A bare raise inside except propagates the original exception instead. Decide whether logging and continuing is real recovery or hidden failure. finally is for cleanup; returning from it can suppress an existing exception or replace a return value.

Test both recovery and cleanup

  1. Add "0" and verify that it is accepted.
  2. Add an empty string and verify failure during int conversion.
  3. Inspect the messages for a nonnumeric input and a negative amount to distinguish their causes.

Exception messages may contain tokens, credentials or personal data. Give users an actionable explanation while keeping diagnostic records limited to what is needed. The logging and debugging guide shows how to record context without treating every detail as suitable for public output.