Try Else and Finally
Core idea
Use else for work that should run after the try block completes normally, without a return, break or continue. Use finally for cleanup on the way out of the statement, whether a handler runs or not. A pending exception continues after finally unless the cleanup changes control flow.
try: count = int("4")except ValueError: print("invalid")else: print(count * 2)finally: print("done")The else branch uses the successfully converted number; finally runs afterward.
Failed path
try: count = int("x")except ValueError: print("invalid")else: print(count * 2)finally: print("done")The handler replaces the success path, while cleanup still runs.
Return still triggers cleanup
def read_count(): try: return 3 finally: print("cleanup")print(read_count())The return value is pending while finally runs, then reaches the caller.
Common mistake
A return inside finally can override an earlier return or suppress an exception. Keep cleanup simple; exceptions raised in else are not handled by the preceding except clauses.
Practice
Change the first example to invalid text and predict the two output lines. Explain why cleanup is not skipped.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Trace cleanup paths
Check your understanding of else and finally.
What is printed?
try: int("3")except ValueError: print("bad")else: print("ok")finally: print("done")What is printed?
try: int("x")except ValueError: print("bad")else: print("ok")finally: print("done")What is printed?
def value(): try: return 9 finally: print("clean")print(value())Why avoid return inside finally?