iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python Try…Except

Errors that happen at runtime are exceptions. Catch them with try / except; clean up with finally.

The shape

PYTHON
try:
    n = int('not a number')
except ValueError as e:
    print('Bad input:', e)
else:
    print('Parsed', n)        # only if no exception
finally:
    print('Always runs')

Catch the specific type

Common exceptionWhen it happens
ValueErrorRight type, wrong value (int('abc')).
TypeErrorWrong type ('a' + 1).
KeyErrorMissing dict key.
IndexErrorList index out of range.
FileNotFoundErrorFile doesn't exist.
ZeroDivisionErrorDivision by zero.

Catch multiple types

PYTHON
try:
    risky()
except (ValueError, KeyError) as e:
    print('handled:', e)

Raising your own

PYTHON
def deposit(amount):
    if amount <= 0:
        raise ValueError(f'amount must be positive: {amount}')

Custom exception classes

PYTHON
class PaymentDeclined(Exception):
    pass

raise PaymentDeclined('Card expired')

Don't swallow exceptions silently

PYTHON
# ✗ Worst form — hides every bug
try:
    work()
except:
    pass

# ✓ At minimum log it
import logging
try:
    work()
except Exception:
    logging.exception('work() failed')
Tip: EAFP — "Easier to Ask Forgiveness than Permission" — is the Pythonic way. Try the operation; catch the specific exception if it fails. Beats checking every precondition first.

Example

Example
try:
    n = int('not a number')
except ValueError as e:
    print('Bad input:', e)
else:
    print('Parsed', n)
finally:
    print('Always runs')
Try it Yourself »

Exercise

Block that always runs after try, regardless of outcome.

try: ... except: ... : cleanup()

Test yourself

Q1. finally runs…
Q2. Bare "except:" is…
Q3. EAFP stands for…

Discussion

Loading…