Repaso
Español
PythonIntermediatePY-26

In try / except / else / finally, when does else run?

Options

  1. Always, right after the try block, whatever happens
  2. Only when an exception was raised inside the try block
  3. Only when no exception was raised inside the try block (Correct option)
  4. Only after finally has finished running its code

Answer

Only if no exception was raised in try

Why

else runs only if the try block finished without an exception.

Put there the code that should run on success, but whose own errors you do NOT want the except above to catch.

finally runs at the end in every case (success or error).

try:
    data = load()
except FileNotFoundError:
    data = {}
else:
    print("loaded", len(data))   # only on success
finally:
    print("done")                # always

Remember

try → except (error) / else (no error) → finally (always).

Key terms

Practice this question in Repaso