all Python 3Exceptionsconstruct
try / except
handling
The try block holds code that may raise an exception. except catches it. else runs if there was none. finally runs always.
Syntax
try:
...
except ErrorType:
...
Catch the specific class: except Exception — and a bare except: even more so — also swallows typos like NameError and turns a bug into a program that quietly does the wrong thing, while a bare except: additionally grabs BaseException, KeyboardInterrupt and SystemExit included. Branch order matters, since the first matching handler wins: except Exception placed before except ValueError makes the later branch unreachable. Keep the try body as small as possible — the more lines it covers, the easier it is to catch an error you never meant to handle.
Examples
try:
x = 1 / 0
except ZeroDivisionError:
print('division by zero') # → division by zero
try:
int('abc')
except ValueError as e:
print(e) # → invalid literal for int() with base 10: 'abc'
# Несколько except: срабатывает первый подходящий
try:
lst = [1, 2, 3]
print(lst[10])
except IndexError:
print('index error') # → index error
except Exception as e:
print('other:', e)
# else — если исключений не было
try:
result = 10 / 2
except ZeroDivisionError:
print('error')
else:
print(result) # → 5.0
# finally — выполняется всегда
try:
f = open('/nonexistent')
except FileNotFoundError:
print('not found') # → not found
finally:
print('always') # → always
# Несколько типов в одном except
try:
x = int(None)
except (TypeError, ValueError) as e:
print(type(e).__name__) # → TypeError
# Exception ловит всё, кроме SystemExit, KeyboardInterrupt и GeneratorExit
try:
raise RuntimeError('oops')
except Exception as e:
print(type(e).__name__, e) # → RuntimeError oops
See also
Open in the full glossarydocs.python.orgReport an inaccuracy