Else (Try)
Python · Exception Handling
Theory
A try statement can have an else block after its except blocks. The else block runs only when the try block finished without raising any exception. If an exception was raised and caught, else is skipped entirely.
In the example, 10 / 2 succeeds, so the except is skipped and else prints 'Success: 5.0'. If the division were 10 / 0, except would print 'Error' and else would not run. Why not put that print inside try? Because code in else is not protected by the except clauses: if it raised its own ZeroDivisionError, that would not be mistaken for the error you meant to catch. Using else keeps the try block focused on the one risky operation and makes the success path explicit.
Why we use it
It separates 'the risky step' from 'what to do once it worked'. This keeps try blocks small and stops your except clauses from accidentally catching errors raised by the follow-up code.
When to use it
Use else when some code should run only if the risky step succeeded, such as processing data after it loaded. If the follow-up is a single trivial line, many developers simply place it after the whole try statement.
How it works
- Run the try block
- Did an exception occur? Yes: Run the matching except block. No: Run the else block.
- Run finally if present
- Continue after the statement
Syntax
try:
...
except Error:
...
else:
...Example
try:
result = 10 / 2
except ZeroDivisionError:
print("Error")
else:
print(f"Success: {result}")Key points
- Keeps success-path code separate from error-handling code
- Skipped entirely if an exception was raised and caught
- Errors inside else are not caught by the same except blocks
- Order is try -> except -> else -> finally
- else requires at least one except clause