Error handling basics
Every AI API call can fail: network timeouts, rate limits, invalid responses. In production AI code, every external call is wrapped in try/except. Let us learn to handle errors gracefully.
Exception handling states
How try/except/else/finally controls error flow
# Basic try/except
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
# Catching multiple exception types
def safe_parse_int(value):
try:
return int(value)
except (ValueError, TypeError) as e:
print(f"Could not parse '{value}': {e}")
return None
print(safe_parse_int("42")) # 42
print(safe_parse_int("hello")) # Nonetry runs the code. except catches specific errors. The "as e" captures the error message. You can catch multiple types with a tuple.
Catching broad Exception works for API calls where you want to handle any failure gracefully. But for logic errors, catch specific types so bugs are not silently hidden. The rule: be specific when you know the error, be broad when wrapping external calls.
# try/except/else/finally: the full pattern
def fake_api_call(should_fail=False):
if should_fail:
raise ConnectionError("Server unreachable")
return {"status": "ok", "data": [1, 2, 3]}
try:
result = fake_api_call(should_fail=False)
except ConnectionError as e:
print(f"API error: {e}")
else:
# Runs only if no exception occurred
print(f"Success! Got {len(result['data'])} items")
finally:
# Always runs, whether exception occurred or not
print("Cleanup always runs")else runs only on success, so use it for code that should only execute when no error happened. finally always runs, making it perfect for cleanup like closing connections.
You can also create your own exceptions using raise, which is how AI agents enforce safety rules. If user input looks dangerous, raise an error before it reaches the LLM.
# Raising your own exceptions
def safe_path(path):
if ".." in path:
raise ValueError(f"Path escapes workspace: {path}")
return path
try:
safe_path("../../etc/passwd")
except ValueError as e:
print(f"Blocked: {e}")raise throws an exception you choose. ValueError is used for invalid inputs. This pattern is common in AI guardrails to block unsafe operations.
AI prompt: Try it with AI
Loading practice…
Quiz: Quiz
Loading practice…