A try statement can have two more clauses. else holds code that should run only when nothing went wrong; finally holds code that must run no matter what. This section also shows what happens when try statements are nested.
The full try statement
Syntax
try: risky codeexcept SomeError: runs if SomeError occurredelse: runs only if NO exception occurred in tryfinally: ALWAYS runs, last
Clause
Runs when
Typical use
try
Always first
Code that may fail
except
A matching exception occurred
Recover or report
else
The try block finished without an exception
Code that depends on the try succeeding
finally
Always: after success, after a handled exception, after an unhandled one, even after return
Clean-up: closing files, releasing connections
Putting success-only code in else rather than at the end of try keeps the try block small, so the except clauses cannot accidentally catch errors from that code.
finally even when the exception is not handled
If no except clause matches, finally still runs, and then the exception continues outward.
Nested try statements
A try statement can be placed inside another. An exception is first offered to the inner except clauses; if none matches, it moves to the outer try. Each level’s finally runs as the exception passes through it.
Key takeaways
else runs only if the try block raised no exception.
finally always runs, last; use it for clean-up.
An unhandled exception still triggers finally, then propagates.
In nested try statements, unhandled exceptions move to the outer level.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write code that opens data.txt, prints its number of lines, reports a missing file with a message, and always prints “Done”.
Show worked answer
try: f = open("data.txt") then except FileNotFoundError: print("data.txt not found"), else: followed by with f: print(len(f.readlines()), "lines"), and finally: print("Done"). If the file is missing, the message and “Done” are printed; otherwise the line count and “Done”. The line counting is in else, so only FileNotFoundError from open is caught.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/exception-handling-in-python-programming/else-finally-and-nested-try-statements/ to read this page.