Python error handling patterns including input validation

by wshobson · MIT license · ★ 39,857 on GitHub · updated Sep 21

Python error handling cover

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)
Claude Codenpx skills add wshobson/agents --skill python-error-handling -g -a claude-code
Claude Code (manual)mkdir -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-handling
Windows (PowerShell)New-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" -Force
Claude.ai / desktopDownload the ZIP and upload it under Settings → Capabilities → Skills.
Codex, Cursor, other agentsPoint them at SKILL.md. The other files are plain text.

Connects with Agent Alley MCP · agentalley.io/mcp

Files included

  • SKILL.md6.0 KB
  • references/1 file · 4.7 KB
Read the files here
wshobson/4236bb92 files
SKILL.md
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

  1. Validate early - Check inputs before expensive operations
  2. Use specific exceptions - ValueError, TypeError, not generic Exception
  3. Include context - Messages should explain what, why, and how to fix
  4. Convert types at boundaries - Parse strings to enums/domain types early
  5. Chain exceptions - Use raise ... from e to preserve debug info
  6. Handle partial failures - Don't abort batches on single item errors
  7. Use Pydantic - For complex input validation with structured errors
  8. Document failure modes - Docstrings should list possible exceptions
  9. Log with context - Include IDs, counts, and other debugging info
  10. Test error paths - Verify exceptions are raised correctly
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---
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="[email protected]",
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 
View all files on GitHub →

Details

Updated
Sep 21, 2026
License
MIT
Stars on the repo
★ 39,857
Checked
Source
wshobson/agents ↗
Creator
wshobson · 179 listings
View creator

Similar skills

See all →
MCPExpert debugging specialist for errors, test failuresDebugger AgentCloudAI-X/claude-workflow-v2 · by CloudAI-XExpert debugging specialist for errors, test failures, crashes, segmentation faults, memory leaks, timeouts, race conditions, deadlocks, and unexpected behavior. Use PROACTIVELY when encountering any error, exception, or failing test. Performs systematic root cause analysis.★ 1.4k GitHub starsSkillEncountering any bug, test failure, or unexpected behaviorSystematic debuggingobra/superpowers · by obraUse when encountering any bug, test failure, or unexpected behavior, before proposing fixes★ 290k GitHub starsSkillRequires running verification commands and confirming outputVerification before completionobra/superpowers · by obraUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always★ 290k GitHub starsSkillGuides systematic root-cause debuggingDebugging and error recoveryaddyosmani/agent-skills · by addyosmaniGuides systematic root-cause debugging. Use when tests fail, builds break, something that worked yesterday broke, behavior doesn't match expectations, or you encounter any unexpected error. Use when you need to figure out what broke and why — a systematic approach to finding and fixing the root cause rather than guessing.★ 98.7k GitHub starsSkillMaster systematic debugging techniques, profiling toolsDebugging strategieswshobson/agents · by wshobsonMaster systematic debugging techniques, profiling tools, and root cause analysis to efficiently track down bugs across any codebase or technology stack. Use when investigating bugs, performance issues, or unexpected behavior.★ 39.9k GitHub starsSkillMaster error handling patterns across languages includingwshobson/agents · by wshobsonMaster error handling patterns across languages including exceptions, Result types, error propagation, and graceful degradation to build resilient applications. Use when implementing error handling, designing APIs, or improving application reliability.★ 39.9k GitHub stars

More from wshobson

SkillMaster C/.NET backend development patterns for buildingwshobson/agents · by wshobsonMaster C#/.NET backend development patterns for building robust APIs, MCP servers, and enterprise applications. Covers async/await, dependency injection, Entity Framework Core, Dapper, configuration, caching, and testing with xUnit. Use when developing .NET backends, reviewing C# code, or designing API architectures.★ 39.9k GitHub starsSkillImplement WCAG 2.2 compliant interfaces with mobileAccessibility compliancewshobson/agents · by wshobsonImplement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.★ 39.9k GitHub starsSkillMaster Material Design 3 and Jetpack Compose patternsAndroid Mobile Designwshobson/agents · by wshobsonMaster Material Design 3 and Jetpack Compose patterns for building native Android apps. Use when designing Android interfaces, implementing Compose UI, or following Google's Material Design guidelines.★ 39.9k GitHub starsSkillMigrate from AngularJS to Angular using hybrid modeAngular migrationwshobson/agents · by wshobsonMigrate from AngularJS to Angular using hybrid mode, incremental component rewriting, and dependency injection updates. Use when upgrading AngularJS applications, planning framework migrations, or modernizing legacy Angular code.★ 39.9k GitHub starsSkillUnderstand anti-reversing, obfuscationAnti reversing techniqueswshobson/agents · by wshobsonUnderstand anti-reversing, obfuscation, and protection techniques encountered during software analysis. Use this skill when analyzing malware evasion techniques, when implementing anti-debugging protections for CTF challenges, when reverse engineering packed binaries, or when building security research tools that need to detect virtualized environments.★ 39.9k GitHub starsSkillBuild production Apache Airflow DAGs with best practicesApache Airflow DAG Patternswshobson/agents · by wshobsonBuild production Apache Airflow DAGs with best practices for operators, sensors, testing, and deployment. Use when creating data pipelines, orchestrating workflows, or scheduling batch jobs.★ 39.9k GitHub stars