else

Introduction

In Python exception handling, the else statement is used along with try and except blocks. The code inside the else block executes only when no exception occurs in the try block.

The else block helps separate the code that should run after a successful operation from the code that handles exceptions.

The else statement is commonly used in:

  • Input validation

  • File handling

  • API testing

  • Automation testing

  • Database operations

  • Data processing

  • Web development

In this tutorial, you will learn about the Python else statement in exception handling, syntax, practical examples, real-world use cases, common mistakes, and best practices.


What is the else Statement?

The else block executes only if the try block completes successfully without raising any exceptions.

Example

try:
    result = 10 / 2

except ZeroDivisionError:
    print("Cannot divide by zero")

else:
    print("Division successful")

Output

Division successful

Since no exception occurred, the else block executed.


Basic Syntax

Syntax

try:
    # Code that may raise an exception

except ExceptionType:
    # Exception handling code

else:
    # Code executed if no exception occurs

Understanding Program Flow

Example

try:
    print("Inside try block")

except:
    print("Inside except block")

else:
    print("Inside else block")

Output

Inside try block
Inside else block

No exception occurred, so the else block ran.


Example with Division

Example

try:
    result = 100 / 5

except ZeroDivisionError:
    print("Division error")

else:
    print("Result =", result)

Output

Result = 20.0

Example with User Input

Example

try:
    age = int(input("Enter your age: "))

except ValueError:
    print("Invalid age")

else:
    print("Your age is:", age)

Sample Input

25

Output

Your age is: 25

Example When Exception Occurs

Example

try:
    age = int("abc")

except ValueError:
    print("Invalid value")

else:
    print("Conversion successful")

Output

Invalid value

Since an exception occurred, the else block was skipped.


Using else with File Handling

Example

try:
    file = open("sample.txt")

except FileNotFoundError:
    print("File not found")

else:
    print("File opened successfully")
    file.close()

Using else with List Operations

Example

try:
    numbers = [10, 20, 30]

    print(numbers[1])

except IndexError:
    print("Invalid index")

else:
    print("List accessed successfully")

Output

20
List accessed successfully

Using else with Dictionary Operations

Example

try:
    student = {
        "name": "John"
    }

    print(student["name"])

except KeyError:
    print("Key not found")

else:
    print("Dictionary lookup successful")

Output

John
Dictionary lookup successful

else Statement in Automation Testing

The else block is often used when a validation succeeds.


Example: API Response Validation

try:
    status_code = 200

    if status_code != 200:
        raise Exception("Invalid status code")

except Exception as error:
    print(error)

else:
    print("API validation passed")

Output

API validation passed

Example: Selenium Element Validation

try:
    element_found = True

    if not element_found:
        raise Exception("Element missing")

except Exception as error:
    print(error)

else:
    print("Element located successfully")

Output

Element located successfully

Example: Test Data Verification

try:
    test_data = int("100")

except ValueError:
    print("Invalid data")

else:
    print("Test data processed successfully")

Output

Test data processed successfully

Real-World Example: ATM Withdrawal

Example

try:
    amount = int(input("Enter amount: "))

except ValueError:
    print("Invalid amount")

else:
    print("Withdrawal request accepted")

Real-World Example: Student Registration

Example

try:
    roll_number = int(input("Enter roll number: "))

except ValueError:
    print("Invalid roll number")

else:
    print("Registration successful")

Real-World Example: Product Quantity

Example

try:
    quantity = int(input("Enter quantity: "))

except ValueError:
    print("Invalid quantity")

else:
    print("Order accepted")

Flow of Execution

Example

try:
    print("Step 1")

except:
    print("Step 2")

else:
    print("Step 3")

Output

Step 1
Step 3

Execution enters the else block only when the try block succeeds.


Difference Between except and else

Feature except else
Executes on Error Yes No
Executes on Success No Yes
Used for Error Handling Yes No
Runs After try Only on Exception Only if No Exception

Common Mistakes Beginners Make

Expecting else to Run After an Exception

Example

try:
    result = 10 / 0

except ZeroDivisionError:
    print("Error")

else:
    print("Success")

Output

Error

The else block does not execute.


Writing Error Handling Inside else

Incorrect

else:
    print("Error occurred")

The else block is for successful execution.


Omitting except Before else

Incorrect

try:
    print("Hello")

else:
    print("Success")

Output

SyntaxError

An else block must follow at least one except block.


Using else for Unrelated Logic

Keep the else block focused on success-related operations.


Best Practices

Use else for Success Scenarios

else:
    print("Operation completed successfully")

Keep Error Handling in except

except ValueError:
    print("Invalid input")

Improve Code Readability

Separating success and failure logic makes code easier to understand.


Use Meaningful Messages

print("File processed successfully")

Keep else Blocks Simple

Avoid placing large amounts of unrelated code inside the else block.


Advantages of else Statements

  • Separates success and failure logic

  • Improves readability

  • Simplifies debugging

  • Makes exception handling cleaner

  • Enhances maintainability


Limitations of else Statements

  • Can only be used with try

  • Requires at least one except block

  • Misuse can reduce readability


Conclusion

The else statement in Python exception handling executes only when no exception occurs in the try block. It helps separate normal program execution from error-handling logic, making code more organized and easier to understand.

Whether you’re validating input, processing files, handling API responses, or creating automation frameworks, the else statement improves code structure and readability.

Mastering the else statement is an important step before learning finally, custom exceptions, exception hierarchies, and advanced error-handling techniques.


Frequently Asked Questions (FAQs)

What is the else statement in exception handling?

The else block executes only when no exception occurs in the try block.

try:
    print("Hello")

except:
    print("Error")

else:
    print("Success")

When does the else block execute?

Only when the try block completes successfully without any exceptions.


Can else be used without except?

No.

An else block must be preceded by at least one except block.


Does else execute if an exception occurs?

No.

The else block is skipped whenever an exception is raised.


Why use else in exception handling?

It separates successful execution logic from error-handling logic, improving readability.


Key Takeaways

  • The else block executes only when no exception occurs.

  • It is used together with try and except.

  • It improves code readability and structure.

  • The else block is skipped if an exception is raised.

  • Error-handling code belongs in except.

  • Success-related code belongs in else.

  • else helps separate normal execution from exception handling.

  • It is widely used in file handling, automation testing, and input validation.

  • An else block cannot exist without an except block.

  • Understanding else is essential before learning the finally statement and advanced exception handling.