Python's exception handling mechanism provides three optional clauses— except
, else
, and finally
— that can be used with the try
clause. Each has a specific purpose and they together offer a robust way to anticipate and manage errors or exceptions in your code. This article focuses on the else
clause, which many programmers find a bit tricky to use or understand.
The else
clause in a try
statement in Python executes if and only if the try
block does not raise an exception. This makes it different from the other two clauses.
Consider the following example:
try:
# attempt this code block
num = int(input("Enter a integer: "))
except ValueError:
# handle exception
print("That's not an integer!")
else:
# executes if the try block does not raise an exception
print("The square of the number is", num**2)
In this example, when you enter a string instead of an integer, a ValueError
exception is raised, and the except
block is executed. However, if you enter an integer, no exception is raised, the try
block successfully completes, and the else
block is executed, printing the square of the entered number.
Contrary to some misconceptions, the else
block is not an alternative to the finally
block. While the else
clause runs when no exceptions occur, the finally
clause always runs, regardless of whether an exception was raised or not.
A best practice when coding in Python is to make use of these exception handling clauses to create resilient programs. The else
clause in a try
block can be particularly handy when there is a certain action that must only take place when no exceptions occur in the try
block, but should not be performed if an exception does occur.
In essence, the else
block helps you segregate the normal flow of your program (the try
block) from your error handling (the except
block), and from actions contingent upon the success of the try
block (the else
block). This leads to cleaner, more maintainable code.