Python error handling patterns including input validation

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…
--- name: python-error-handling 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. --- # Python Error Handling Build robust Python applications with proper input validation, meaningful exceptions, and graceful failure handling. Good error handling makes debugging easier and systems more reliable. ## When to Use This Skill - Validating user input and API parameters - Designing exception hierarchies for applications - Handling partial failures in batch operations - Converting external data to domain types - Building user-friendly error messages - Implementing fail-fast validation patterns
Overview
Build robust Python applications with proper input validation, meaningful exceptions, and graceful failure handling. Good error handling makes debugging easier and systems more reliable.
Manual install (npx, ZIP)
npx skills add wshobson/agents --skill python-error-handling -g -a claude-codemkdir -p ~/.claude/skills && curl -sL https://codeload.github.com/wshobson/agents/tar.gz/4236bb91f839 \
| tar -xz -C ~/.claude/skills --strip-components=4 agents-4236bb91f839/plugins/python-development/skills/python-error-handlingNew-Item -ItemType Directory -Force "$HOME\.claude\skills" | Out-Null; Invoke-WebRequest "https://m.agentalley.io/zip/a19ee4452c9450e3f338/python-error-handling.zip" -OutFile "$env:TEMP\python-error-handling.zip"; Expand-Archive "$env:TEMP\python-error-handling.zip" -DestinationPath "$HOME\.claude\skills" -ForceConnects with Agent Alley MCP · agentalley.io/mcp
Files included
SKILL.md6.0 KBreferences/1 file · 4.7 KB
Read the files here
Show the full text194 lines
Python Error Handling
Build robust Python applications with proper input validation, meaningful exceptions, and graceful failure handling. Good error handling makes debugging easier and systems more reliable.
When to Use This Skill
- Validating user input and API parameters
- Designing exception hierarchies for applications
- Handling partial failures in batch operations
- Converting external data to domain types
- Building user-friendly error messages
- Implementing fail-fast validation patterns
Core Concepts
1. Fail Fast
Validate inputs early, before expensive operations. Report all validation errors at once when possible.
2. Meaningful Exceptions
Use appropriate exception types with context. Messages should explain what failed, why, and how to fix it.
3. Partial Failures
In batch operations, don't let one failure abort everything. Track successes and failures separately.
4. Preserve Context
Chain exceptions to maintain the full error trail for debugging.
Quick Start
def fetch_page(url: str, page_size: int) -> Page:
if not url:
raise ValueError("'url' is required")
if not 1 <= page_size <= 100:
raise ValueError(f"'page_size' must be 1-100, got {page_size}")
# Now safe to proceed...
Fundamental Patterns
Pattern 1: Early Input Validation
Validate all inputs at API boundaries before any processing begins.
def process_order(
order_id: str,
quantity: int,
discount_percent: float,
) -> OrderResult:
"""Process an order with validation."""
# Validate required fields
if not order_id:
raise ValueError("'order_id' is required")
# Validate ranges
if quantity <= 0:
raise ValueError(f"'quantity' must be positive, got {quantity}")
if not 0 <= discount_percent <= 100:
raise ValueError(
f"'discount_percent' must be 0-100, got {discount_percent}"
)
# Validation passed, proceed with processing
return _process_validated_order(order_id, quantity, discount_percent)
Pattern 2: Convert to Domain Types Early
Parse strings and external data into typed domain objects at system boundaries.
from enum import Enum
class OutputFormat(Enum):
JSON = "json"
CSV = "csv"
PARQUET = "parquet"
def parse_output_format(value: str) -> OutputFormat:
"""Parse string to OutputFormat enum.
Args:
value: Format string from user input.
Returns:
Validated OutputFormat enum member.
Raises:
ValueError: If format is not recognized.
"""
try:
return OutputFormat(value.lower())
except ValueError:
valid_formats = [f.value for f in OutputFormat]
raise ValueError(
f"Invalid format '{value}'. "
f"Valid options: {', '.join(valid_formats)}"
)
# Usage at API boundary
def export_data(data: list[dict], format_str: str) -> bytes:
output_format = parse_output_format(format_str) # Fail fast
# Rest of function uses typed OutputFormat
...
Pattern 3: Pydantic for Complex Validation
Use Pydantic models for structured input validation with automatic error messages.
from pydantic import BaseModel, Field, field_validator
class CreateUserInput(BaseModel):
"""Input model for user creation."""
email: str = Field(..., min_length=5, max_length=255)
name: str = Field(..., min_length=1, max_length=100)
age: int = Field(ge=0, le=150)
@field_validator("email")
@classmethod
def validate_email_format(cls, v: str) -> str:
if "@" not in v or "." not in v.split("@")[-1]:
raise ValueError("Invalid email format")
return v.lower()
@field_validator("name")
@classmethod
def normalize_name(cls, v: str) -> str:
return v.strip().title()
# Usage
try:
user_input = CreateUserInput(
email="[email protected]",
name="john doe",
age=25,
)
except ValidationError as e:
# Pydantic provides detailed error information
print(e.errors())
Pattern 4: Map Errors to Standard Exceptions
Use Python's built-in exception types appropriately, adding context as needed.
| Failure Type | Exception | Example |
|---|---|---|
| Invalid input | ValueError |
Bad parameter values |
| Wrong type | TypeError |
Expected string, got int |
| Missing item | KeyError |
Dict key not found |
| Operational failure | RuntimeError |
Service unavailable |
| Timeout | TimeoutError |
Operation took too long |
| File not found | FileNotFoundError |
Path doesn't exist |
| Permission denied | PermissionError |
Access forbidden |
# Good: Specific exception with context
raise ValueError(f"'page_size' must be 1-100, got {page_size}")
# Avoid: Generic exception, no context
raise Exception("Invalid parameter")
Detailed worked examples and patterns
Detailed sections (starting with ## Advanced Patterns) live in references/details.md. Read that file when the navigation summary above is insufficient.
Best Practices Summary
- Validate early - Check inputs before expensive operations
- Use specific exceptions -
ValueError,TypeError, not genericException - Include context - Messages should explain what, why, and how to fix
- Convert types at boundaries - Parse strings to enums/domain types early
- Chain exceptions - Use
raise ... from eto preserve debug info - Handle partial failures - Don't abort batches on single item errors
- Use Pydantic - For complex input validation with structured errors
- Document failure modes - Docstrings should list possible exceptions
- Log with context - Include IDs, counts, and other debugging info
- Test error paths - Verify exceptions are raised correctly
| 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 | |
| 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 | |
| 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 | |
| 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 | |
| 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="[email protected]", |
| 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 | |
| 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 | **Validate early** - Check inputs before expensive operations |
| 185 | **Use specific exceptions** - `ValueError`, `TypeError`, not generic `Exception` |
| 186 | **Include context** - Messages should explain what, why, and how to fix |
| 187 | **Convert types at boundaries** - Parse strings to enums/domain types early |
| 188 | **Chain exceptions** - Use `raise ... from e` to preserve debug info |
| 189 | **Handle partial failures** - Don't abort batches on single item errors |
| 190 | **Use Pydantic** - For complex input validation with structured errors |
| 191 | **Document failure modes** - Docstrings should list possible exceptions |
| 192 | **Log with context** - Include IDs, counts, and other debugging info |
| 193 | **Test error paths** - Verify exceptions are raised correctly |
| 194 |
Details
- Updated
- Sep 21, 2026
- License
- MIT
- Stars on the repo
- ★ 39,857
- Checked
- Source
- wshobson/agents ↗
- Creator
- wshobson · 179 listings
Similar skills
See all →
MCPExpert debugging specialist for errors, test failuresDebugger Agent
SkillEncountering any bug, test failure, or unexpected behaviorSystematic debugging
SkillRequires running verification commands and confirming outputVerification before completion
SkillGuides systematic root-cause debuggingDebugging and error recovery
SkillMaster systematic debugging techniques, profiling toolsDebugging strategies
SkillMaster error handling patterns across languages includingMore from wshobson
SkillMaster C/.NET backend development patterns for building
SkillImplement WCAG 2.2 compliant interfaces with mobileAccessibility compliance
SkillMaster Material Design 3 and Jetpack Compose patternsAndroid Mobile Design
SkillMigrate from AngularJS to Angular using hybrid modeAngular migration
SkillUnderstand anti-reversing, obfuscationAnti reversing techniques
SkillBuild production Apache Airflow DAGs with best practicesApache Airflow DAG Patterns