Skills · Coding

Python Error Handling

Unverified31/40

Python error handling patterns including input validation, exception hierarchies, and partial failure handling. Use when implementing validation logic, designing exception strategies, handling batch processing failures, or building robust APIs.

Originally by wshobson · MIT

Claude CodePartialHas SKILL.md but declares no allowed-tools — Claude Code will ask for permission each time
CursorPartialPlain prose you can paste in — but no Cursor rules file
CodexPartialPlain prose you can paste in — but no AGENTS.md
Gemini CLIPartialPlain prose you can paste in
CopilotPartialPlain prose you can paste in — but no Copilot instructions file
npx agentalley add python-error-handling

This command does not work yet — the CLI is still being built. Until then, use Raw in the reader below to take the file.

Who is stuck, and on what

Python error handling patterns including input validation, exception hierarchies, and partial failure handling. Use when implementing validation logic, designing exception strategies, handling batch processing failures, or building robust APIs.

The whole source

No sign-in, no blur, nothing truncated
python-error-handling/SKILL.md194 lines6.0 KBRawView on GitHub
Frontmatter — 2 properties
namepython-error-handling
descriptionPython error handling patterns including input validation, exception hierarchies, and partial failure handling. Use when implementing validation logic, designing exception strategies, handling batch processing failures, or building robust APIs.
1---
2name: python-error-handling
3description: Python error handling patterns including input validation, exception hierarchies, and partial failure handling. Use when implementing validation logic, designing exception strategies, handling batch processing failures, or building robust APIs.
4---A5No allowed-tools declared — no way to tell what this skill may touch
5 
6# Python Error Handling
7 
8Build robust Python applications with proper input validation, meaningful exceptions, and graceful failure handling. Good error handling makes debugging easier and systems more reliable.
9 
10## When to Use This Skill
11 
12- Validating user input and API parameters
13- Designing exception hierarchies for applications
14- Handling partial failures in batch operations
15- Converting external data to domain types
16- Building user-friendly error messages
17- Implementing fail-fast validation patterns
18 
19## Core Concepts
20 
21### 1. Fail Fast
22 
23Validate inputs early, before expensive operations. Report all validation errors at once when possible.
24 
25### 2. Meaningful Exceptions
26 
27Use appropriate exception types with context. Messages should explain what failed, why, and how to fix it.
28 
29### 3. Partial Failures
30 
31In batch operations, don't let one failure abort everything. Track successes and failures separately.
32 
33### 4. Preserve Context
34 
35Chain exceptions to maintain the full error trail for debugging.
36 
37## Quick Start
38 
39```python
40def fetch_page(url: str, page_size: int) -> Page:
41 if not url:
42 raise ValueError("'url' is required")
43 if not 1 <= page_size <= 100:
44 raise ValueError(f"'page_size' must be 1-100, got {page_size}")
45 # Now safe to proceed...
46```
47 
48## Fundamental Patterns
49 
50### Pattern 1: Early Input Validation
51 
52Validate all inputs at API boundaries before any processing begins.
53 
54```python
55def process_order(
56 order_id: str,
57 quantity: int,
58 discount_percent: float,
59) -> OrderResult:
60 """Process an order with validation."""
61 # Validate required fields
62 if not order_id:
63 raise ValueError("'order_id' is required")
64 
65 # Validate ranges
66 if quantity <= 0:
67 raise ValueError(f"'quantity' must be positive, got {quantity}")
68 
69 if not 0 <= discount_percent <= 100:
70 raise ValueError(
71 f"'discount_percent' must be 0-100, got {discount_percent}"
72 )
73 
74 # Validation passed, proceed with processing
75 return _process_validated_order(order_id, quantity, discount_percent)
76```
77 
78### Pattern 2: Convert to Domain Types Early
79 
80Parse strings and external data into typed domain objects at system boundaries.
81 
82```python
83from enum import Enum
84 
85class OutputFormat(Enum):
86 JSON = "json"
87 CSV = "csv"
88 PARQUET = "parquet"
89 
90def parse_output_format(value: str) -> OutputFormat:
91 """Parse string to OutputFormat enum.
92 
93 Args:
94 value: Format string from user input.
95 
96 Returns:
97 Validated OutputFormat enum member.
98 
99 Raises:
100 ValueError: If format is not recognized.
101 """
102 try:
103 return OutputFormat(value.lower())
104 except ValueError:
105 valid_formats = [f.value for f in OutputFormat]
106 raise ValueError(
107 f"Invalid format '{value}'. "
108 f"Valid options: {', '.join(valid_formats)}"
109 )
110 
111# Usage at API boundary
112def export_data(data: list[dict], format_str: str) -> bytes:
113 output_format = parse_output_format(format_str) # Fail fast
114 # Rest of function uses typed OutputFormat
115 ...
116```
117 
118### Pattern 3: Pydantic for Complex Validation
119 
120Use Pydantic models for structured input validation with automatic error messages.
121 
122```python
123from pydantic import BaseModel, Field, field_validator
124 
125class CreateUserInput(BaseModel):
126 """Input model for user creation."""
127 
128 email: str = Field(..., min_length=5, max_length=255)
129 name: str = Field(..., min_length=1, max_length=100)
130 age: int = Field(ge=0, le=150)
131 
132 @field_validator("email")
133 @classmethod
134 def validate_email_format(cls, v: str) -> str:
135 if "@" not in v or "." not in v.split("@")[-1]:
136 raise ValueError("Invalid email format")
137 return v.lower()
138 
139 @field_validator("name")
140 @classmethod
141 def normalize_name(cls, v: str) -> str:
142 return v.strip().title()
143 
144# Usage
145try:
146 user_input = CreateUserInput(
147 email="user@example.com",
148 name="john doe",
149 age=25,
150 )
151except ValidationError as e:
152 # Pydantic provides detailed error information
153 print(e.errors())
154```
155 
156### Pattern 4: Map Errors to Standard Exceptions
157 
158Use Python's built-in exception types appropriately, adding context as needed.
159 
160| Failure Type | Exception | Example |
161|--------------|-----------|---------|
162| Invalid input | `ValueError` | Bad parameter values |
163| Wrong type | `TypeError` | Expected string, got int |
164| Missing item | `KeyError` | Dict key not found |
165| Operational failure | `RuntimeError` | Service unavailable |
166| Timeout | `TimeoutError` | Operation took too long |
167| File not found | `FileNotFoundError` | Path doesn't exist |
168| Permission denied | `PermissionError` | Access forbidden |
169 
170```python
171# Good: Specific exception with context
172raise ValueError(f"'page_size' must be 1-100, got {page_size}")
173 
174# Avoid: Generic exception, no context
175raise Exception("Invalid parameter")
176```
177 
178## Detailed worked examples and patterns
179 
180Detailed sections (starting with `## Advanced Patterns`) live in `references/details.md`. Read that file when the navigation summary above is insufficient.
181 
182## Best Practices Summary
183 
1841. **Validate early** - Check inputs before expensive operations
1852. **Use specific exceptions** - `ValueError`, `TypeError`, not generic `Exception`
1863. **Include context** - Messages should explain what, why, and how to fix
1874. **Convert types at boundaries** - Parse strings to enums/domain types early
1885. **Chain exceptions** - Use `raise ... from e` to preserve debug info
1896. **Handle partial failures** - Don't abort batches on single item errors
1907. **Use Pydantic** - For complex input validation with structured errors
1918. **Document failure modes** - Docstrings should list possible exceptions
1929. **Log with context** - Include IDs, counts, and other debugging info
19310. **Test error paths** - Verify exceptions are raised correctly
194 

Reviews

Installed this one?Write the first review and take the Trailblazer badge.

Reviews only open after a real install, so this is empty — and we leave it empty rather than invent one.

Alternatives

Also in Coding