liveBook · Manning

Else clause

As explained in The Quick Python Book, Fourth Edition

An else clause is the optional part of a try statement that executes only when its try block completes without raising an exception.

In a try statement, the optional else clause runs only when the try block completes without raising an exception. It keeps successful-path code separate from exception-handling code. section 3.4.7 section 14.2.3

Use the clause with these rules:

  • Execute the try body first; run else only if no caught exception occurs. section 14.2.3
  • Handle failures in except clauses, rather than placing ordinary successful-case processing inside try. section 3.4.7
  • Run finally afterward when present, whether the operation raised an exception or completed successfully. section 3.4.7
  • Remember that else is optional and belongs after the except clauses in the compound statement. section 14.2.3

Process a file only after a successful read

A file-processing loop can open a file and read its first line in try, report IOError or EmptyFileError in except, print the line in else, and announce completion in finally. An empty file raises the custom exception, so the else block is skipped; a successfully read line reaches else. section 3.4.7

try:
   body
except exception_type1 as var1:
   exception_code1
except exception_type2 as var2:
   exception_code2
except (exception_type3, exception_type4  as var3:
   exception_code3
   .
except:
   default_exception_code
else:
   else_body
finally:
   finally_body

Use the syntax listing to see the else clause positioned between exception handlers and finally. section 14.2.3

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines execution order and syntax, then demonstrates file handling without pursuing implementation internals.
Examples
Demonstrates file opening, line reading, IOError handling, EmptyFileError handling, and completion reporting.
What you can do after
Apply it via Python's try-except-else-finally syntax to run code only after an operation succeeds.
How it connects
Connects try statements with exceptions, exception handlers, finally clauses, and custom exception classes.

Also explained in

Compare how 5 books explain else clause →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.