# Catch multiple types in one excepttry:
d = {}
print(d["key"])
except (KeyError, IndexError) as e:
print(f"Lookup failed: {type(e).__name__}: {e}")
# Exception hierarchytry:
int("abc")
except Exception as e:
print(f"Caught via base class: {type(e).__name__}: {e}")
# Order matters: specific before generaldefsafe_convert(value):
try:
returnint(value)
except ValueError:
print(f" ValueError for {value!r}")
returnNoneexcept TypeError:
print(f" TypeError for {value!r}")
returnNoneexcept Exception as e:
print(f" Unexpected: {e}")
returnNonefor v in ["42", "abc", None, 3.14]:
print(f"{v!r} -> {safe_convert(v)}")
Output
Click "Run" to execute your code
Catch specific exceptions first, then broader ones. All exceptions inherit from BaseException; most user-facing ones inherit from Exception.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?