try / except
Handle errors gracefully instead of crashing.
Syntax
try:
...
except ValueError:
...When something goes wrong, Python raises an exception. If nothing handles it, the program stops. A try/except block lets you catch the error and respond.
The parts
try— the code that might fail.except— runs if a matching error occurs.else— runs if no error occurred.finally— always runs, for cleanup.
Example
def safe_divide(a, b):
try:
result = a / b
except ZeroDivisionError:
return 'Cannot divide by zero'
else:
return result
finally:
print('Done')
print(safe_divide(10, 2))
print(safe_divide(10, 0))
# Output:
# Done
# 5.0
# Done
# Cannot divide by zeroWhen to use it
- An API client wraps a network request in try/except to return a friendly message on timeout.
- A file loader catches FileNotFoundError to prompt the user to provide a valid path.
- A type-safe parser catches ValueError when int() fails on malformed user input.
More examples
Basic try/except
Catches a ZeroDivisionError and prints a user-friendly message instead of crashing.
try:
result = 10 / 0
except ZeroDivisionError:
print('Cannot divide by zero')
# Output:
# Cannot divide by zeroMultiple except clauses
Handles two different exception types in separate except clauses for precise error messages.
def parse_age(s):
try:
age = int(s)
return 100 // age
except ValueError:
print('Not a valid number')
except ZeroDivisionError:
print('Age cannot be zero')
parse_age('abc') # Not a valid number
parse_age('0') # Age cannot be zerotry / except / else / finally
Shows the full try/except/else/finally structure: else runs on success, finally always runs.
try:
f = open('data.txt')
except FileNotFoundError:
print('File missing')
else:
content = f.read()
print('Read', len(content), 'chars')
finally:
print('Done (always runs)')
Discussion