Sub topic 6
Running the success path in else
This chapter assumes you can write try/except blocks, know that except clauses are checked in order, and have read a basic traceback. It covers the else clause of a try statement: what it does, when it helps, and where it differs from simply writing more code inside try.
What else does on a try statement
A try statement can have an else clause. It runs only when the try block finishes without raising an exception. It must come after every except clause and before finally.
def parse_port(text):
try:
port = int(text)
except ValueError:
print(f"{text!r} is not a number")
return None
else:
if not 0 < port < 65536:
raise ValueError(f"port out of range: {port}")
return port
finally:
print("parse_port finished")
print(parse_port("8080"))
print(parse_port("abc"))The output is:
parse_port finished
8080
'abc' is not a number
parse_port finished
NoneFor "8080", int() succeeds, so the else block runs the range check and returns. The finally block still prints before the caller receives the value. For "abc", int() raises ValueError, the handler runs, and else is skipped. finally runs on both paths.
The execution order is:
- The
tryblock runs. - If it raised, the first matching
exceptruns, andelseis skipped. - If it did not raise,
elseruns. finallyruns last in every case.
Why not just put the code in try
Putting the success code at the end of the try block often seems to work. The difference is which exceptions the handlers can see. An except clause catches exceptions from the whole try block, but never from the else block. An exception raised in else goes straight to the caller (after finally runs).
Here is a version that keeps everything in try:
def parse_age(text):
try:
age = int(text)
if age < 0:
raise ValueError("age cannot be negative")
return age
except ValueError:
print("not a number")
return None
print(parse_age("-5"))This prints not a number and returns None, though -5 is a number. The ValueError raised by the validation was caught by the handler meant for int(). The message is wrong and the real problem is hidden.
Moving the validation into else fixes this:
def parse_age(text):
try:
age = int(text)
except ValueError:
print("not a number")
return None
else:
if age < 0:
raise ValueError("age cannot be negative")
return age
try:
parse_age("-5")
except ValueError as exc:
print(f"rejected: {exc}")Now the output is rejected: age cannot be negative. The except clause only guards the one call it was written for.
The rule behind this is to keep the try block as small as possible, ideally the single operation whose failure you plan to handle. The else block holds what depends on that operation succeeding, and it is not covered by the handlers.
A practical pattern: open, then use
Opening a file is a typical case. You want to handle a missing file, but you do not want that handler to also swallow errors from processing the contents.
def count_lines(path):
try:
f = open(path, encoding="utf-8")
except FileNotFoundError:
print(f"no such file: {path}")
return 0
else:
with f:
return sum(1 for _ in f)
print(count_lines("missing.txt"))If open() fails, the handler reports it. If it succeeds, else takes ownership of the file object with a with statement, which closes it when the block exits. Any UnicodeDecodeError raised while reading is not caught here, because it comes from else. If you did want to handle it, you would add a second try around the read, and its scope would be visible in the code.
else inside loops
In a loop, else pairs well with continue in the handler. The failure path skips the rest of the iteration, and the success path stays on the left margin of its own block.
def total(values):
result = 0
for raw in values:
try:
number = float(raw)
except ValueError:
print(f"skipping {raw!r}")
continue
else:
result += number
return result
print(total(["1.5", "x", "2"]))The output is skipping 'x' followed by 3.5. The continue in the handler is not strictly needed here, since else already keeps the addition off the failure path. In real code, though, the loop body often has more statements after the try, and continue skips those too.
When else does not run
else runs only if control reaches the end of the try block normally. If the try block leaves early, else is skipped:
def first_even(numbers):
for n in numbers:
try:
if n % 2 == 0:
return n
except TypeError:
continue
else:
print(f"{n} is odd")
return None
print(first_even([3, 5, 8]))The output is:
3 is odd
5 is odd
8For 3 and 5, the try block finishes normally and else prints. For 8, the return leaves the function from inside try, so else never runs. The same applies to break and continue inside the try block. A common mistake is to expect else to run "after success" when the success path ends in return.
The related rule for finally is the opposite: it runs even when try returns, which is why it is the place for cleanup.
Exceptions raised in else
An exception raised in else is not handled by the sibling except clauses of the same try statement, but finally still runs:
def divide_total(text):
try:
n = int(text)
except ValueError:
return None
else:
return 100 // n
finally:
print("done")
try:
divide_total("0")
except ZeroDivisionError:
print("caller handled it")The output is done, then caller handled it. If you want both operations guarded, use an outer try, or separate try statements, rather than trying to make the handlers on one statement cover else.
Rules and restrictions
elserequires at least oneexceptclause. Atrywith onlyelseorfinallyand noexceptis a syntax error. If you do not need a handler, you do not needelseeither.- There can be at most one
elseclause, and it must follow allexceptclauses. elsealso works withexcept*in Python 3.11 and later, with the same meaning.- Variables assigned in
tryare visible inelse, as shown withageandfabove. Variables bound byexcept ... as nameare deleted when their handler ends and are never available inelse.
When to use it and when to skip it
Use else when the code after the risky call depends on its success and could itself raise an exception of the same type the handler catches. The parse_age case is the typical one.
Skip it when the follow-up code is trivial and cannot raise the handled exception types. A try block that ends in return value is clear enough, and an else that holds one line of arithmetic adds structure without adding safety. Narrowing the except clause (for example except FileNotFoundError instead of except OSError) often removes the same problem.
Another option is to return from the handler and put the success code after the try statement:
def parse_port_simple(text):
try:
port = int(text)
except ValueError:
return None
return portThis is equivalent when every handler exits the function, and it reads well. else is better when handlers fall through (they log and the code continues), because without it the code after the statement would also run on the failure path.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Placing `else` before `except` | `SyntaxError` | Order is `try`, `except`, `else`, `finally` |
| Adding `else` to a `try` with only `finally` | `SyntaxError` | Add an `except`, or drop the `else` |
| Expecting `else` after a `return` in `try` | `else` is skipped | Put the work before the `return`, or use `finally` for cleanup |
| Expecting `except` to catch errors from `else` | The error reaches the caller | Wrap in an outer `try` if you want to handle it |
| Using `else` to hold cleanup | Cleanup skipped on errors | Use `finally` or a `with` statement |
Exercise
The function below prints "invalid" for the input "-3", although "-3" is a valid integer. Rewrite it with an else clause so that "-3" raises ValueError("must be positive") to the caller, and "abc" still prints "invalid" and returns None. def to_positive(text): try: n = int(text) if n <= 0: raise ValueError("must be positive") return n except ValueError: print("invalid") return None
Show answer
Move the check out of the try block: def to_positive(text): try: n = int(text) except ValueError: print("invalid") return None else: if n <= 0: raise ValueError("must be positive") return n Exceptions raised in else are not caught by the except clauses of the same try statement. So "-3" propagates a ValueError with the message "must be positive", while "abc" fails inside int(), is caught, and returns None.
Exercise
In this code, does the line print("clean") ever run for the call find([1, 2, 3], 2)? Explain why. def find(items, target): for item in items: try: if item == target: return item except TypeError: pass else: print("clean") return None
Show answer
Yes, it runs once, for the item 1. The try block finishes normally for 1, so else prints "clean". For 2, the return statement leaves the function from inside the try block, so else is skipped. The loop never reaches 3.