In try / except / else / finally, when does else run?
Options
- Always, right after the
tryblock, whatever happens - Only when an exception was raised inside the
tryblock - Only when no exception was raised inside the
tryblock (Correct option) - Only after
finallyhas 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") # alwaysRemember
try → except (error) / else (no error) → finally (always).