Exceptions
Raise and handle errors with try/except. In LLD, define custom exception classes and raise them for invalid state; in DSA, try is rare but useful for parsing input or catching KeyError/IndexError.
Syntax
try:
x = int(s)
except ValueError:
x = 0
else and finally
try:
f = open(path)
except OSError as e:
print("failed:", e)
else:
data = f.read() # runs only if no exception
f.close()
finally:
print("always runs")
Multiple excepts
try:
v = d[key] / count
except KeyError:
v = None
except ZeroDivisionError:
v = 0
except (TypeError, ValueError) as e: # tuple: any of these
raise
except Exception as e: # catch-all last; avoid bare `except:`
print(type(e).__name__, e)
Without parentheses (3.14+)
try:
v = int(s)
except ValueError, TypeError: # 3.14+ (PEP 758), only without `as`
v = 0
raise
def withdraw(balance: int, amount: int) -> int:
if amount > balance:
raise ValueError(f"insufficient funds: {balance} < {amount}")
return balance - amount
try:
...
except KeyError:
raise # re-raise the current exception
Custom exceptions
class ParkingLotFullError(Exception):
pass
class InvalidMoveError(ValueError):
def __init__(self, move: str):
super().__init__(f"invalid move: {move}")
self.move = move
raise ... from (chaining)
class ConfigError(Exception): ...
def load(cfg: dict, key: str) -> str:
try:
return cfg[key]
except KeyError as e:
raise ConfigError(f"missing {key}") from e # sets __cause__
# raise X from None -> suppress the original context
except* (exception groups, 3.11+)
try:
raise ExceptionGroup("batch", [ValueError("a"), TypeError("b")])
except* ValueError as eg:
print("values:", eg.exceptions)
except* TypeError as eg:
print("types:", eg.exceptions)
# Mostly for concurrent code (asyncio.TaskGroup); rarely needed otherwise
Common built-in exceptions
| Exception | Description |
|---|---|
ValueError | An operation receives the right type but an invalid value, such as int("abc"). |
TypeError | An operation receives an unsupported type, such as adding a string to an integer. Also raised for incorrect function arguments. |
KeyError | A mapping key is missing, such as accessing d["missing"] when that key is not in the dictionary. |
IndexError | A sequence index is out of range, such as accessing items[3] in a three-item list. Out-of-range slices do not raise this error. |
ZeroDivisionError | Division or modulo uses a zero divisor, such as 10 / 0, 10 // 0, or 10 % 0. |
AttributeError | An attribute lookup or assignment fails, such as accessing obj.name when the object has no such attribute. |
StopIteration | An iterator has no more items. Raised by next(it) without a default and handled automatically by a for loop. |
RecursionError | Execution exceeds Python's maximum recursion depth, often because recursive calls have no reachable base case. |
NotImplementedError | A method or operation is intended to be implemented but is not yet available, often in a base class that requires a subclass override. |