Sub topic 6
Running the success path in else
This chapter assumes you can write and call Python functions, read a simple traceback, and use try and except with specific exception types. It covers the else clause of a try statement, which holds code that should run only when the try block raised nothing.
The shape of try with else
A try statement can have an else clause after all its except clauses. Python runs else only if the try block finished without an exception. If any handler ran, or the try block exited early through return, break, or continue, else is skipped.
def read_count(text):
try:
count = int(text)
except ValueError:
print(f"{text!r} is not a number")
return None
else:
print(f"parsed {count}")
return count
read_count("12")
read_count("twelve")For "12", the output is parsed 12. For "twelve", the handler prints the error message and else never runs.
Why not put the code at the end of try?
You could write the success code as the last lines of the try block. The result looks the same, but the behavior differs. Any exception raised in those extra lines would be caught by your except clauses, even though those clauses were written for a different failing line.
def average(text, total):
try:
count = int(text)
result = total / count
except ValueError:
print("count must be a whole number")
return None
return resultHere total / count can raise ZeroDivisionError. That error is not a ValueError, so it escapes, which is correct in this case. The risk appears when a handler is broad. If it were except Exception, a bug in the division line would be reported as a bad count. Keeping the try block to the one risky call avoids this.
The else clause lets you keep the try block small without losing the success logic.
def average(text, total):
try:
count = int(text)
except ValueError:
print("count must be a whole number")
return None
else:
return total / count
print(average("4", 10))An exception raised inside else is not handled by the except clauses of the same try statement. It propagates to the caller, which is what you want for errors you did not plan for.
else together with finally
When finally is present, it runs after else. The order is try, then else on success (or except on failure), then finally.
def open_first_line(path):
try:
f = open(path)
except FileNotFoundError:
print("no such file")
return None
else:
try:
return f.readline()
finally:
f.close()The open call is the only line in try. The file is closed only when it was actually opened, which a finally attached to the first try could not guarantee without extra checks.
Common errors
- Writing
elsewithout anyexceptorfinally. This is a syntax error. Atryneeds at least one of them. - Expecting
elseto run after a handled error. It runs only on success. - Expecting
exceptto catch errors raised inelse. It does not. - Using
elsefor code that does not depend on thetrysucceeding. Place that code after the whole statement instead.
Exercise
In the code below, what is printed when text is "0"? Explain which clause handles the problem.
def inverse(text):
try:
n = int(text)
except ValueError:
return "not a number"
else:
return 1 / n
print(inverse("0"))
Show answer
Nothing is printed by print, because the program ends with a traceback for ZeroDivisionError: division by zero. int("0") succeeds, so else runs. The division fails inside else, and the except ValueError clause does not cover errors raised in else, so the exception propagates to the caller.