try:
value =int("not_a_number")exceptValueErroras 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.
defsafe_divide(a:float, b:float)->float|None:try:
result = a / b
exceptZeroDivisionError:print("Cannot divide by zero")returnNoneelse:print(f"Result: {result}")return result
finally:print("Division attempted")safe_divide(10,3)safe_divide(10,0)
Output
Result: 3.3333333333333335
Division attempted
Cannot divide by zero
Division attempted
Note else runs only when no exception occurred. finally always runs, even after return statements. Use else to keep the try block minimal.
defvalidate(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:raiseExceptionGroup("Validation failed", errors)try:validate({})except*ValueErroras 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.
# ValueError - wrong value for the type# TypeError - wrong type entirely# KeyError - missing dictionary key# IndexError - list index out of range# AttributeError - missing attribute# FileNotFoundError - file doesn't exist# PermissionError - insufficient permissions# StopIteration - iterator exhaustedtry:open("nonexistent.txt")exceptFileNotFoundError:print("File not found")
Output
File not found
Note Learn the hierarchy: FileNotFoundError is a subclass of OSError. Catching OSError also catches FileNotFoundError, PermissionError, etc.
from contextlib import suppress
withsuppress(ExceptionType):...
Example
from contextlib import suppress
import os
# Instead of try/except/passwithsuppress(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.