Skip to main content

The else Block in try-except

You already know that try runs risky code and except handles errors. But what if you want to run some code only when no error occurred?

That is exactly what the else block does.


When Does else Run?

The else block runs only if the try block completes successfully without raising any exception.

try:
number = int(input("Enter a number: "))
except ValueError:
print("That is not a valid number!")
else:
# This runs ONLY if no error occurred in try
print(f"You entered: {number}")
finally:
print("Input process complete.")

If user enters 42:

You entered: 42
Input process complete.

If user enters hello:

That is not a valid number!
Input process complete.

Why Not Just Put Code Inside try?

Beginners often ask: "Why not put the success code inside the try block itself?"

The answer: Separation of concerns. Code inside try should only contain the risky operation. Code in else should contain what happens after success. This prevents accidentally catching errors that were not from the risky operation.

# ❌ Problem: Both lines are inside try
try:
data = int(input("Enter age: "))
print(data / 0) # Bug! But except catches it silently
except ValueError:
print("Bad input")

# ✅ Better: Only risky code in try, success logic in else
try:
data = int(input("Enter age: "))
except ValueError:
print("Bad input")
else:
print(data / 0) # Bug is NOT hidden — it crashes visibly

The Complete Flow: try-except-else-finally

try: → Run risky code
except: → Handle specific errors (if any)
else: → Run only if NO error occurred
finally: → Always run (cleanup)
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"Division successful! Result: {result}")
finally:
print("Calculation attempt finished.")

Output:

Division successful! Result: 5.0
Calculation attempt finished.

Quick Summary

  • else Block: Executes only when the try block succeeds without raising any exceptions.
  • Separation of Concerns: Keep only risky statements in try, and place dependent success logic in else.
  • Full Pattern Architecture: try (attempt) -> except (catch) -> else (on success) -> finally (always cleanup).

What's Next?

Now that we know how to catch exceptions, let's learn how to trigger our own exceptions manually using the raise keyword in the next lesson!