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




