MCS-201 · Unit 14

Exception Handling in Python Programming

Section 3 of 5

Block 4 · Unit 14Exception Handling in Python Programming9 min · Section 3 of 5

14.3else, finally and Nested try Statements

Covers IGNOU MCS-201 §14.3

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 code
except SomeError:
    runs if SomeError occurred
else:
    runs only if NO exception occurred in try
finally:
    ALWAYS runs, last
ClauseRuns whenTypical use
tryAlways firstCode that may fail
exceptA matching exception occurredRecover or report
elseThe try block finished without an exceptionCode that depends on the try succeeding
finallyAlways: after success, after a handled exception, after an unhandled one, even after returnClean-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 1 · multiple choice

When does an else clause of a try statement run?

Show answer

Answer: C. Only when the try block completes without an exception

else is for code that should run only after the risky part succeeded.

Question 2 · multiple choice

What does this program print?

Python · quiz_finally.py
def f():
    try:
        return "from try"
    finally:
        print("cleaning up")

print(f())
Show answer

Answer: B. cleaning up, then from try

finally runs before the function actually returns, so its print appears first; then the returned value is printed.

Question 3 · multiple choice

What does this program print?

Python · quiz_else.py
try:
    x = int("7")
except ValueError:
    print("bad")
else:
    print("good", x)
finally:
    print("end")
Show answer

Answer: C. good 7, end

The conversion succeeds, so else runs, followed by finally.

Question 4 · multiple choice

An exception raised in an inner try is not matched by its except clauses. What happens?

Show answer

Answer: D. The inner finally runs, then the exception is offered to the outer try’s handlers

Exceptions propagate outward level by level, running each finally on the way.

Question 5 · multiple choice

Which is a typical use of finally?

Show answer

Answer: B. Closing a file or database connection whether or not an error occurred

Clean-up code must run in every case, which is exactly what finally guarantees.

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.

↑ ↓ move↵ openTab switch type