Part 14 / Topic 6 of 7
Errors and retries
The SDK raises typed exceptions, and the type tells you what to do:
# examples/05_handle_errors_with_specific_exception_types.py (ran against the local mock)
try:
client.messages.create(model="claude-does-not-exist", ...)
except anthropic.NotFoundError as e:
print("not found (fix the request, do not retry):", e.status_code) # 404
except anthropic.RateLimitError:
print("rate limited: back off and retry")
except anthropic.APIStatusError as e:
print("other API error:", e.status_code)
except anthropic.APIConnectionError:
print("network problem: retry later")
The rule: 4xx (except 429) = your request is wrong — fix it, don't retry. 429 and 5xx and network errors = transient — retry with exponential backoff. The SDK already retries some transient failures itself; configure max_retries rather than wrapping blind loops.
🧪 Quick quiz
- A request names a model that does not exist. What should your code do?
Show the answer
Fix the request — a 404 is not retryable (verified: the SDK raised anthropic.NotFoundError with status 404). Retry 429 and 5xx, not 400/404.
Done here? The practice set for Part 14 — 4 exercises with solutions — is on the part page.