except — Intermediate Examples
Catches and handles exceptions raised in a try block
Multiple exceptions and hierarchy
Catching exception groups and using inheritance.
python
# Catch multiple types in one except try: d = {} print(d["key"]) except (KeyError, IndexError) as e: print(f"Lookup failed: {type(e).__name__}: {e}") # Exception hierarchy try: int("abc") except Exception as e: print(f"Caught via base class: {type(e).__name__}: {e}") # Order matters: specific before general def safe_convert(value): try: return int(value) except ValueError: print(f" ValueError for {value!r}") return None except TypeError: print(f" TypeError for {value!r}") return None except Exception as e: print(f" Unexpected: {e}") return None for v in ["42", "abc", None, 3.14]: print(f"{v!r} -> {safe_convert(v)}")
Catch specific exceptions first, then broader ones. All exceptions inherit from BaseException; most user-facing ones inherit from Exception.
except with else and finally
The complete try/except/else/finally pattern.
python
import json def parse_json(text): try: data = json.loads(text) except json.JSONDecodeError as e: print(f" Parse error: {e.msg}") return None except TypeError: print(" Input must be a string") return None else: print(f" Parsed successfully: {type(data).__name__}") return data finally: print(" Cleanup done") print("Test 1:") parse_json('{"key": "value"}') print("Test 2:") parse_json("not json {") print("Test 3:") parse_json(None)
else runs only when no exception occurred. finally runs always. Together they create a complete error handling pattern.
Want to try these examples interactively?
Open Intermediate Playground