
Python Error Handling
FreeEnhance your Python apps with robust error management.
Free · Opens the source repo
What Python Error Handling does
The Python Error Handling skill provides essential patterns and best practices for managing errors in Python applications. It focuses on techniques for input validation, exception hierarchies, and handling partial failures, making it a valuable resource for developers aiming to build reliable and maintainable software. By implementing these strategies, you can ensure that your applications handle unexpected situations gracefully, improving user experience and reducing debugging time.
This skill is particularly useful when designing APIs or working with user inputs, as it emphasizes the importance of validating data early in the process. By adopting a fail-fast approach, you can catch errors before they escalate into more significant issues. The skill also covers how to create meaningful exceptions that provide context, making it easier for developers to understand and resolve problems when they arise.
In addition to basic error handling, the skill introduces advanced patterns, such as preserving context in exceptions and managing partial failures in batch operations. This ensures that your applications can continue functioning even when some operations fail, which is crucial for maintaining robustness in complex systems. The included examples demonstrate how to implement these patterns effectively, allowing you to apply them directly to your projects.
Overall, this skill is designed for Python developers and designers who want to improve their error handling practices, whether they are building APIs, processing user inputs, or managing complex data operations. By following the guidelines and patterns outlined in this skill, you can create applications that are not only more reliable but also easier to debug and maintain.
When to use it
Use this skill when implementing validation logic, designing exception strategies, or handling batch processing failures in your Python projects.
When not to use it
This skill may not be suitable for very simple scripts or applications where error handling is not a concern.
What you can build with it
Validating User Input in APIs
Implement early validation for all user inputs to ensure data integrity before processing.
Designing Exception Hierarchies
Create a structured approach to exceptions that enhances error reporting and debugging.
Handling Batch Processing Failures
Track successes and failures in batch operations, allowing for resilient processing even when some items fail.
How to install Python Error Handling
View source1. Install with the skills CLI
npx skills add wshobson/agents/python-error-handling --agent claude-code2. Or install it manually
Download the skill folder and drop it into ~/.claude/skills/ for all projects, or .claude/skills/ to scope it to one repo. Restart Claude Code so it picks up the new skill.
Anthropic's agentic coding CLI, and the reference implementation of Agent Skills. Drop a skill folder into ~/.claude/skills and Claude Code loads it automatically whenever a task matches the skill's description. Claude Code docs
Inside SKILL.md
Written by wshobsonPython 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="user@example.com",
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
Frequently asked questions about Python Error Handling
Similar skills
Agent Host Debug Logs
Analyze Agent Host debug logs for deeper insights.
Code OSS Dev - Launch + Debug
Launch and debug Code OSS with isolated profiles.
Phoenix CLI
Debug LLM applications with structured analysis tools.
Power Automate Debugging
Diagnose and fix Power Automate flow errors effectively.
Arize Trace
Inspect and export traces for LLM applications.
Runtime Behavior Probe
Investigate real runtime behavior with precision.
