try...except...else in Python

In Python, the else block in exception handling is often misunderstood. It is not required, but it is extremely useful for writing clean and readable code.

Basic Syntax

try:
    # Code that might raise an exception
except SomeException:
    # Code that runs if an exception occurs
else:
    # Code that runs ONLY if no exception occurs    

Explanation

Think of it as: “If everything went fine, then execute this part.”

Example: Basic try-except-else

Python

try:
    # Code that may cause an error
    num = int(input("Enter a number: "))  # May raise ValueError if input is not numeric
except ValueError:
    # Runs if an error occurs
    print("That's not a valid number!")
else:
    # Runs only if no exception occurs
    print(f"You entered {num}, which is valid.")    

Output Examples

If user inputs 10:

Output

You entered 10, which is valid.    

If user inputs abc:

Output

That's not a valid number!    

Example: File Handling with else

Python

try:
    file = open("data.txt", "r")
except FileNotFoundError:
    print("File not found!")
else:
    # Only runs if file was opened successfully
    print("File opened successfully!")
    content = file.read()
    print(content)
    file.close()    

Why use else here? The file operations (read, close) only make sense if the file opened correctly. So, it is safer to place them in the else block instead of the try block.

Example: With finally

Python

try:
    result = 10 / 2
except ZeroDivisionError:
    print("Cannot divide by zero.")
else:
    print("Division successful! Result =", result)
finally:
    print("Execution finished (this always runs).")    

Output:

Output

Division successful! Result = 5.0
Execution finished (this always runs).    

When to Use else

Common Mistake

Do not put code that might raise an error inside the else block. The else block should contain code that is expected to run safely.

Summary

BlockRuns WhenExample Use
tryCode that may cause an errorRisky code execution
exceptWhen an error occursError handling logic
elseWhen no error occursFollow-up successful logic
finallyAlways runsCleanup resources (files, DB, etc.)