try:
value = int("not_a_number")
except ValueError as e:
print(f"Conversion failed: {e}")
# Multiple exception typestry:
result = {"a": 1}["b"]
except (KeyError, IndexError) as e:
print(f"Lookup error: {e}")
output
Conversion failed: invalid literal for int() with base 10: 'not_a_number'
Lookup error: 'b'
Note Always catch specific exceptions. Bare 'except:' catches everything including SystemExit and KeyboardInterrupt, which is almost never what you want.
raise ExceptionGroup(msg, [exc1, exc2])
except* ErrorType as eg:
example
def validate(data: dict) -> None:
errors = []
ifnot data.get("name"):
errors.append(ValueError("name is required"))
ifnot data.get("email"):
errors.append(ValueError("email is required"))
if errors:
raise ExceptionGroup("Validation failed", errors)
try:
validate({})
except* ValueError as eg:
for err in eg.exceptions:
print(f" - {err}")
output
- name is required
- email is required
Note except* catches matching exceptions from the group while letting others propagate. ExceptionGroup is ideal for concurrent/batch operations that produce multiple errors.
from contextlib import suppress
with suppress(ExceptionType):
...
example
from contextlib import suppress
import os
# Instead of try/except/passwith suppress(FileNotFoundError):
os.remove("temp_cache.dat")
print("Cleanup done")
output
Cleanup done
Note contextlib.suppress is cleaner than try/except/pass when you intentionally want to ignore specific exceptions. Do not suppress broad exception types.