all Python 3Exceptionsconstruct
else in try-except
handling
The else block runs only if no exception was raised inside try. It separates the happy path from error handling.
Syntax
try:
...
except Error:
...
else:
# только при успехе
The point of else isn't tidiness but narrowing the risk zone: lines moved out of try are no longer covered by that except, so a ValueError raised while carrying on can't be silently swallowed by a handler written for parsing. An else clause needs at least one except (else on its own is a syntax error), and the order is try, then else, then finally. Leaving try via return, break or continue skips else entirely.
Examples
try:
result = int('42')
except ValueError:
print('error')
else:
print(f'success: {result}') # → success: 42
def safe_open(path):
try:
f = open(path)
except FileNotFoundError:
return None
else:
with f:
return f.read()
print(safe_open('/нет/такого/файла')) # → None
# else + finally
try:
x = 10 / 2
except ZeroDivisionError:
print('zero division')
else:
print(f'result: {x}') # → result: 5.0
finally:
print('done') # → done
import json
def parse(s):
try:
data = json.loads(s)
except json.JSONDecodeError:
print('invalid JSON')
else:
return data
print(parse('{"a": 1}')) # → {'a': 1}
print(parse('{')) # → invalid JSON, затем None
# В else — только код, который НЕ должен ловиться этим except
try:
n = int('5')
except ValueError:
print('not a number')
else:
print(n * 2) # → 10
See also
Open in the full glossarydocs.python.orgReport an inaccuracy