Skip to content

Module 12 · Exception Handling — topic 6 of 11

else

The else clause of try: code that runs only when no exception occurred, why it keeps try blocks small, and how it differs from putting code at the end of the try block.

Beginner 6 min read·Lesson 188 of 306 in Python Programming

Learning objectives

  • Use else for success-only code
  • Explain why else is better than extending the try block
  • Combine try, except and else

Definition

The optional else clause of a try statement runs only if the try block completed without raising an exception. Exceptions raised inside else are not handled by that statement's except clauses.

Introduction

'Try to open the file; if that fails, report it; otherwise, process its contents.' That 'otherwise' is exactly what the else clause expresses.

Why it matters

else lets you keep the try block down to the one risky operation while still running follow-up code only on success — clearer code and fewer accidentally caught errors.

Detailed explanation

Order of clauses: try, then except clauses, then else, then finally (if any).

The else block runs when the try block finishes normally — no exception and no return, break or continue leaving it early.

Exceptions raised in the else block are not caught by the except clauses above it. That is the point: those handlers were meant for the risky line only.

Compared with putting the same code at the end of the try block, else avoids misattributing errors from follow-up code.

Compared with putting the code after the whole try statement, else makes it obvious that it should run only when the operation succeeded.

else is optional and not always needed; use it when there is a clear success-only step.

Loops also have an else clause (run when the loop wasn't broken); the two ideas are similar — 'no interruption happened'.

Syntax

Python
try:
n = int(text)
except ValueError:
print("invalid")
else:
print("doubled:", n * 2) # only on success
  • else runs only if try succeeded.
  • Its errors aren't caught by the except clauses.
  • Keeps try minimal.

Code examples

Success-only code

Python
for text in ["8", "eight"]:
try:
n = int(text)
except ValueError:
print(text, "-> invalid")
else:
print(text, "-> doubled is", n * 2)
Output
8 -> doubled is 16
eight -> invalid

Returning from each branch

Python
def process(data):
try:
value = data["amount"]
except KeyError:
return "no amount"
else:
return f"amount is {value:.2f}"
print(process({"amount": 12.5}), "|", process({}))
Output
amount is 12.50 | no amount

More examples

Parsing settings

Python
import json
def load_settings(text):
try:
data = json.loads(text)
except json.JSONDecodeError as e:
print(f"bad JSON at line {e.lineno} col {e.colno}: {e.msg}")
return None
else:
data.setdefault("theme", "light")
print("loaded", sorted(data))
return data
load_settings('{"lang": "en"}')
load_settings('{"lang": "en",}')
Output
loaded ['lang', 'theme']
bad JSON at line 1 col 14: Illegal trailing comma before end of object

Step-by-step explanation

  • Only json.loads is inside try, because only parsing errors should be reported as bad JSON.
  • Adding defaults and printing happen in else, which runs only when parsing worked.
  • JSONDecodeError provides the line, column and message of the problem.

Expected output

Running “Parsing settings” prints exactly:

TextOutput
loaded ['lang', 'theme']
bad JSON at line 1 col 14: Illegal trailing comma before end of object

Practical applications

  • Open a file in try, process it in else.
  • Fetch data in try, update the cache in else.

Best practices

  • Use else for steps that depend on the try block succeeding.
  • Keep the try block to the operation you're guarding.
  • Don't use else when a simple sequence is clearer.

Common mistakes

Follow-up code inside try

Avoid

try:
data = json.loads(text)
data["theme"].upper() # a KeyError here...
except (json.JSONDecodeError, KeyError):
print("bad JSON") # ...is misreported

Prefer

try:
data = json.loads(text)
except json.JSONDecodeError:
print("bad JSON")
else:
data.get("theme", "light").upper()

else keeps errors from follow-up code separate.

Important notes

  • try statements may combine all four clauses: try / except / else / finally.

Key takeaways

  • else runs only when try raised nothing.
  • Its exceptions are not handled by the same except clauses.
  • It keeps try blocks small and intent clear.

Try it yourself

  1. 1
    Read a number from a list of strings; in else, print whether it is even or odd.
  2. 2
    Rewrite a try block that contains three lines so that only the risky one is protected and the rest go in else.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

10 questions cover the “Exception Handling” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhat is printed?
Practise this module