Python Error Handling

Python Error Handling

Teaches an AI coding agent robust Python error handling: early input validation, exception hierarchies, partial failure handling and clear error messages.

Skill files2 files

references/

SKILL.md194 lines
1
---
2
name: python-error-handling
3
description: 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
---
5
6
# Python Error Handling
7
8
Build 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
23
Validate inputs early, before expensive operations. Report all validation errors at once when possible.
24
25
### 2. Meaningful Exceptions
26
27
Use appropriate exception types with context. Messages should explain what failed, why, and how to fix it.
28
29
### 3. Partial Failures
30
31
In batch operations, don't let one failure abort everything. Track successes and failures separately.
32
33
### 4. Preserve Context
34
35
Chain exceptions to maintain the full error trail for debugging.
36
37
## Quick Start
38
39
```python
40
def 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
52
Validate all inputs at API boundaries before any processing begins.
53
54
```python
55
def 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
80
Parse strings and external data into typed domain objects at system boundaries.
81
82
```python
83
from enum import Enum
84
85
class OutputFormat(Enum):
86
JSON = "json"
87
CSV = "csv"
88
PARQUET = "parquet"
89
90
def 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
112
def 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
120
Use Pydantic models for structured input validation with automatic error messages.
121
122
```python
123
from pydantic import BaseModel, Field, field_validator
124
125
class 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
145
try:
146
user_input = CreateUserInput(
147
email="user@example.com",
148
name="john doe",
149
age=25,
150
)
151
except ValidationError as e:
152
# Pydantic provides detailed error information
153
print(e.errors())
154
```
155
156
### Pattern 4: Map Errors to Standard Exceptions
157
158
Use 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
172
raise ValueError(f"'page_size' must be 1-100, got {page_size}")
173
174
# Avoid: Generic exception, no context
175
raise Exception("Invalid parameter")
176
```
177
178
## Detailed worked examples and patterns
179
180
Detailed 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
184
1. **Validate early** - Check inputs before expensive operations
185
2. **Use specific exceptions** - `ValueError`, `TypeError`, not generic `Exception`
186
3. **Include context** - Messages should explain what, why, and how to fix
187
4. **Convert types at boundaries** - Parse strings to enums/domain types early
188
5. **Chain exceptions** - Use `raise ... from e` to preserve debug info
189
6. **Handle partial failures** - Don't abort batches on single item errors
190
7. **Use Pydantic** - For complex input validation with structured errors
191
8. **Document failure modes** - Docstrings should list possible exceptions
192
9. **Log with context** - Include IDs, counts, and other debugging info
193
10. **Test error paths** - Verify exceptions are raised correctly
194

© Seth Hobson · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 11,962 prompts

More by @OpenSourceBuffGuy

See all
Ancient Civilization Miniature Diorama prompt image

Ancient Civilization Miniature Diorama

Draws a realistic miniature diorama of an ancient civilization's monuments under construction, set on blueprints atop a wooden drafting table.

image-prompt, gpt-image, miniature, photorealistic, architecture, history, blueprint, 3d-render, cinematic, natural-light, vertical-format, placeholders, long-form, construction, still-life, bokeh, architectural-rendering, for-artists, concept-art, fantasy-world

Error Handling Patterns prompt image

Error Handling Patterns

Teaches an AI agent resilient error handling across languages: exceptions versus Result types, propagation, retries, circuit breakers and graceful degradation.

agent-skill, best-practices, coding, backend, api, debugging, design-patterns, distributed-systems, clean-code, code, code-generation, software-architecture, troubleshooting, for-developers, advanced, long-form, cheat-sheet, guardrails, observability, refactoring, site-reliability, microservices, error-handling

Riot Ink Screenprint Collage prompt image

Riot Ink Screenprint Collage

Defines a reusable JSON style for punk-zine screenprint posters: a thresholded photo hero, black, yellow and red spot inks, a huge headline band and painted marks.

image-prompt, json-prompt, placeholders, poster, collage, printmaking, typography, structured-output, style-reference, limited-palette, vibrant-colors, black-and-white, film-grain, text-rendering, vertical-format, long-form, advanced, for-designers, for-artists, graphic-design, portrait, album-cover, doodle

Reviews

Loading reviews…

Discussion

Loading comments…