Python’s else in try-except Statements

Introduction

As in loops and conditionals, the else clause can be optionally added to a tryexcept statements. The else in tryexcept Python statements functions to execute a code block when an exception does not occur. Its purpose is to isolate only the code that is prone to causing the handled exception within the try block. Consequently, it contributes to code clarity by making it easier to identify where the protection of the try is applied.

Syntax the else Clause in try-except Statement

The else clause is positioned after the try and except clauses and before the finally clause, if there is one. When the else is used, the except clause must be present. (As you may recall from the lesson about the finally clause, the except is optional if a finally is used. However, this is no longer the case with an else.)

Here is a summary of the try statement with all its clauses (in the order they must appear), including the else:

try:
    try-block
except ExceptionType:
    except-block
else:
    else-block
finally:
    finally-block
  • try: Initiates the try statement.
  • try-block: Contains the code that might raise an exception.
  • except: Handles exceptions that occur within the try block. (Can be omitted if a finally clause is present, but mandatory with an else.)
  • except-block: Code executed when an exception is caught.
  • else: An optional clause that defines a block of code to execute if no exceptions occur in the try block.
  • else-block: Code executed when no exceptions are raised.
  • finally: An optional clause that defines a block of code to executed regardless of whether an exception occurs or not.
  • finally-block: Code executed regardless of exceptions. Contains cleanup code or final operations to execute.

Utilizing the else Clause

The else clause provides a way to execute code only if no exceptions occur in the try block. This is useful for scenarios where specific actions should be taken when the anticipated operations succeed without raising any exceptions.

Let’s illustrate the usage of the else clause with an example. Consider a scenario where we attempt to open a file, perform some operations, and print a success message if the file is opened successfully.

Example:

try:
    file = open("example.txt", "r")
except FileNotFoundError:
    print("File not found.")
else:
    print("File successfully opened.")
    content = file.read()
    print("File content:", content)
finally:
    print("File closed.")
    file.close()

Output 1:

File not found.
File closed.

Output 2:

File successfully opened.
File content: This is what's in the file!
File resource clean up.

In the example above, the try block attempts to open a file named “example.txt” in read mode. If the file does not exist, a FileNotFoundError is caught and handled by the except block (line 4), printing an appropriate message, as demonstrated by Output 1.

If the file is opened successfully, as is the case in Output 2, the else block (lines 6-8) executes, printing a success message and file’s content. The finally block (line 10-11) ensures that the file is closed, regardless of whether any exception occurred or not.

Significance of the else Clause

The else clause in a tryexcept statement allows for a clear distinction between code that may raise exceptions that the except handles, and code that won’t. It provides a means of isolating code that does not trigger the handled exceptions, thereby enhancing code readability and maintainability. Specifically, the code within the else block should concentrate on operations that rely on the successful execution of the try block.

To demonstrate the utility of the else clause, let’s reimagine the previous example without incorporating the else in the tryexcept statement.

Example:

try:
    file = open("example.txt", "r")
    
    print("File successfully opened.")
    content = file.read()
    print("File content:", content)
except FileNotFoundError:
    print("File not found.")
finally:
    print("File closed.")
    file.close()

In the revised code, the else clause has been omitted, and all its corresponding code relocated to the bottom of the try block, starting on line 4. Functionally, the program operates identically because when an exception occurs in a try block, all subsequent code is skipped. Despite working the same way, now the try block contains code that does not raise the FileNotFoundError exception the except handles.

Summary & Reference for the Python else Clause in try-except Statements

The else clause in try-except statements allows for the execution of specific code when no exceptions occur within the try block.


The else clause is placed after the try and except clauses, but before the finally clause, if one exists.

try:
    try-block
except ExceptionType:
    except-block
else:
    else-block
finally:
    finally-block

When using the else clause, the except clause becomes mandatory, unlike when using the finally clause, where the except becomes optional.


The else clause helps isolate the code that can cause the handled exceptions. This separation improves code readability and maintainability.

try:
    file = open("example.txt", "r")
except FileNotFoundError:
    print("File not found.")
else:
    print("File successfully opened.")
    content = file.read()
    print("File content:", content)
finally:
    print("File closed.")
    file.close()

It’s important to utilize the else clause judiciously, focusing on operations contingent on the successful execution of the try block.