Python Try Except Else – Complete Guide with Examples

Introduction

While most developers are familiar with try and except, Python also includes an else block that can make exception handling more organized and readable.

The else block is executed only when no exception occurs in the try block. This allows developers to separate normal program logic from error-handling logic, resulting in cleaner and more maintainable code.

What is Python Try Except Else?

Python Try Except Else is an exception-handling structure that allows you to:

  • Test code using the try block
  • Handle errors using the except block
  • Execute code when no exception occurs using the else block

Basic Structure


try:
    # Risky code
except ExceptionType:
    # Error handling code
else:
    # Runs if no exception occurs

The else block provides a clear separation between successful execution and error handling.

Why Use Else with Try Except?

Without else, successful code often gets mixed with exception-handling code.

Example Without Else


try:
    number = int(input("Enter a number: "))
    print("Number:", number)
except ValueError:
    print("Invalid input")

This works, but the successful execution code is inside the try block.

Example With Else


try:
    number = int(input("Enter a number: "))
except ValueError:
    print("Invalid input")
else:
    print("Number:", number)

This makes the code easier to understand.

Syntax

The syntax of Try Except Else is:


try:
    # Code that may raise an exception
except ExceptionType:
    # Handle exception
else:
    # Execute if no exception occurs

Example:


try:
    age = int(input("Enter age: "))
except ValueError:
    print("Please enter a valid number")
else:
    print("Age entered:", age)

How Try Except Else Works?

Execution follows these steps:

  1. Python executes the try block.
  2. If an exception occurs, the matching except block runs.
  3. If no exception occurs, the else block runs.
  4. The program continues execution.

Flow Diagram


try block
    |
    |
No Exception?
   / \
 Yes  No
  |    |
else  except

Simple Example

Example:


try:
    number = int(input("Enter a number: "))
except ValueError:
    print("Invalid input")
else:
    print("You entered:", number)

Input:


25

Output:

You entered: 25

Since no exception occurred, the else block executed.

Example with ValueError

A ValueError occurs when invalid input is converted.

Example:


try:
    age = int("Python")
except ValueError:
    print("Invalid age")
else:
    print("Age accepted")

Output:

Invalid age

The else block is skipped because an exception occurred.

Example with Division

Example:


try:
    result = 100 / 5
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("Result:", result)

Output:

Result: 20.0

No exception occurs, so the else block runs.

Example with User Input

Example:


try:
    num1 = int(input("Enter first number: "))
    num2 = int(input("Enter second number: "))
    result = num1 / num2
except ValueError:
    print("Enter valid numbers")
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("Result:", result)

Input:


20
4

Output:

Result: 5.0

Multiple Except Blocks with Else

A program can contain multiple except blocks and one else block.

Example:


try:
    numbers = [10, 20, 30]
    print(numbers[1])
except IndexError:
    print("Invalid index")
except TypeError:
    print("Type error")
else:
    print("Operation successful")

Output:

20
Operation successful

Try Except Else with File Handling

File operations often use else.

Example:


try:
    file = open("students.txt", "r")
except FileNotFoundError:
    print("File not found")
else:
    print(file.read())
    file.close()

Output:

John
Alice
David

The file is read only when it opens successfully.

Using Finally with Try Except Else

The finally block executes whether an exception occurs or not.

Syntax


try:
    pass
except:
    pass
else:
    pass
finally:
    pass

Example:


try:
    result = 10 / 2
except ZeroDivisionError:
    print("Error")
else:
    print("Success")
finally:
    print("Program completed")

Output:

Success
Program completed

Difference Between Else and Finally

Many beginners confuse else and finally.

Block Purpose
else Executes only if no exception occurs
finally Always executes

Example:


try:
    result = 10 / 0
except ZeroDivisionError:
    print("Error")
else:
    print("Success")
finally:
    print("Finished")

Output:

Error
Finished

Notice that else did not execute, but finally did.

Complete Example


try:
    username = input("Enter username: ")
    if len(username) < 3:
        raise ValueError(
            "Username too short"
        )
except ValueError as e:
    print(e)
else:
    print("Registration successful")

Input:


John

Output:

Registration successful

Real-life Example

Imagine you are developing an online examination system.

Students enter their marks, and the system calculates the percentage.


try:
    marks = int(
        input("Enter marks: ")
    )
    percentage = (marks / 100) * 100
except ValueError:
    print("Invalid marks")
else:
    print(
        "Percentage:",
        percentage
    )

Input:


85

Output:

Percentage: 85.0

Why Is This Useful?

Educational software must validate user input and handle errors without crashing. The else block keeps successful operations separate from error handling.

Other real-world applications include:

  • Login systems
  • Banking software
  • ATM applications
  • Inventory management
  • Student portals
  • E-commerce websites

Common Mistakes

1. Putting Else Before Except

Incorrect:


try:
    pass
else:
    pass
except:
    pass

Output:

SyntaxError

Correct:


try:
    pass
except:
    pass
else:
    pass

2. Using Else Without Except

Incorrect:


try:
    pass
else:
    pass

Output:

SyntaxError

An else block requires at least one except block.

3. Putting Risky Code in Else

Incorrect:


else:
    result = 10 / 0

The else block should contain code that executes after successful completion of the try block.

4. Catching Every Exception

Incorrect:


except:
    print("Error")

Correct:


except ValueError:
    print("Invalid input")

Use specific exceptions whenever possible.

5. Ignoring Error Information

Incorrect:


except Exception:
    print("Error")

Correct:


except Exception as e:
    print(e)

Provides useful debugging details.

Best Practices

1. Use Else for Successful Operations


else:
    print("Operation successful")

Keeps code organized.

2. Use Specific Exceptions


except ValueError:

Improves readability and debugging.

3. Keep Try Blocks Small


Only include code that may generate exceptions.

4. Use Meaningful Messages


print("Please enter a valid number")

Improves user experience.

5. Combine Else with Finally When Needed


else:
    print("Success")
finally:
    print("Cleanup complete")

Provides better control over program flow.

Difference Between Try, Except, Else, and Finally

Block Purpose
try Contains risky code
except Handles exceptions
else Executes if no exception occurs
finally Always executes

Conclusion

Python Try Except Else provides a structured way to handle errors while keeping successful execution code separate from error-handling code. The try block contains risky operations, the except block handles exceptions, and the else block executes only when everything runs successfully.

Using else improves code readability, reduces confusion, and makes applications easier to maintain. It is especially useful in programs involving user input, file handling, calculations, databases, and web applications.

Related Python Tutorials