✨ Python else Block in Exception Handling β€” Run Code Only When No Errors Occur

Introduction 🌟

In Python’s exception-handling structure, the else block is used to run code **only when no exception occurs** inside the try block. This helps separate normal logic from error-handling logic.

Note

πŸ’‘ Think of else as:
β€œIf everything went fine, run this.”

1. Basic try–except–else Structure 🧱

basic_else.py

try:
    x = int("10")
except ValueError:
    print("❌ Conversion error!")
else:
    print("βœ” Success! Converted number =", x)

βœ” else runs only when try has **no errors**.

2. Else + Finally 🎯

else_finally.py

try:
    num = 10 / 2
except ZeroDivisionError:
    print("❌ Cannot divide by zero!")
else:
    print("βœ” Division successful:", num)
finally:
    print("πŸŽ‰ Done")

Note

βœ” finally runs always
βœ” else runs only when no exception occurs

3. Why Use Else Block? πŸ€”

  • βœ” Keeps try block small and focused
  • βœ” Separates error-handling from normal logic
  • βœ” Makes code cleaner and easier to understand
  • βœ” Prevents catching exceptions accidentally inside success code

4. Example: Input Handling πŸ”€

input_else.py

try:
    age = int(input("Enter age: "))
except ValueError:
    print("❌ Please enter a valid number!")
else:
    print("βœ” You entered:", age)

5. Example: File Reading πŸ“

file_else.py

try:
    f = open("data.txt")
except FileNotFoundError:
    print("❌ File not found!")
else:
    content = f.read()
    print("βœ” File successfully read!")
    print(content)
finally:
    print("Closing program...")

6. Example: Database Operation πŸ”Œ

db_else.py

try:
    print("Connecting to database...")
    connected = True
except ConnectionError:
    print("❌ Cannot connect!")
else:
    print("βœ” Connected successfully!")
    # Perform DB operations

7. Else Is NOT Executed If Any Exception Happens ❌

else_not_run.py

try:
    x = 10 / 0
except ZeroDivisionError:
    print("❌ Error occurred")
else:
    print("βœ” This will NOT run")

8. Best Practice: Keep try Block Minimal πŸ’‘

try_minimal.py

# ❌ Bad practice
try:
    x = int(input())
    y = x / 2
    print("Result:", y)
except ValueError:
    print("Invalid input!")

βœ” Better approach:

try_with_else.py

try:
    x = int(input())
except ValueError:
    print("Invalid input!")
else:
    print("Result:", x / 2)

9. Else Block in Loops πŸ”

else in loops runs only when the loop ends normally (without break). But here we focus on exception-handling else.

10. When to Use Else Block? 🎯

  • βœ” When success logic should run only if no errors occur
  • βœ” When try block handles risky code
  • βœ” When you want clear separation between β€œrisky” and β€œsafe” code

Conclusion πŸŽ‰

>>β€œThe else block makes your exception handling clean β€” letting you clearly separate success paths from error paths.” ✨

You now fully understand the Else Block in Python! Want the next topic? Try Custom Exceptions, Raising Exceptions, Error Hierarchy, or File Handling. Just tell me! 😊