Agent skill

Python Error Handling

by wshobson in wshobson/agents

Python error handling patterns including input validation, exception hierarchies, and partial failure handling.

MITAuto-check passedDevelopment

Install Python Error Handling

skills CLI
$ npx skills add wshobson/agents --skill python-error-handling -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install wshobson/agents python-error-handling --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/wshobson/agents.git skills-src && mkdir -p .claude/skills && cp -r skills-src/plugins/python-development/skills/python-error-handling .claude/skills/python-error-handling && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
python-error-handling
GitHub stars
40k
Token cost
~1.5k tokens
SKILL.md length
379 words
Files
2 (incl. references)
Skills in repo
142
Repo updated
First seen
Licence
MIT

At a glance

Python error handling patterns including input validation, exception hierarchies, and partial failure handling.

  • Works in 4 steps: Fail Fast → Meaningful Exceptions → Partial Failures → …
  • Implementing validation logic
  • SKILL.md covers When to Use This Skill, Core Concepts, Quick Start and Fundamental Patterns, plus 2 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

Python Error Handling is an agent skill from wshobson/agents. 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.

Its SKILL.md is about 1.5k tokens, which your agent loads only when the skill is triggered. The skill folder holds 2 other files, including reference files (for example `references/details.md`).

It sits in Development, covering Error handling and Data pipelines and ETL. It works with Python. The repository describes itself as: Multi-harness agentic plugin marketplace for Claude Code, Codex, Cursor, OpenCode, GitHub Copilot, Google Antigravity, and Pi. The licence is MIT.

When your agent uses it

  • Implementing validation logic
  • Designing exception strategies
  • Handling batch processing failures
  • Building robust APIs

Example prompts

  • “/python-error-handling”

Requirements

  • Python 3

Workflow steps

4 steps, taken from the step headings in SKILL.md.

  1. Fail Fast
  2. Meaningful Exceptions
  3. Partial Failures
  4. Preserve Context

What it can do on your machine

Read from SKILL.md and the folder at commit 46891e7. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are python).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Python Error Handling loads about 1.5k tokens when it runs, and up to ~2.7k if it reads all its reference files. Until then it costs about 67 tokens; SKILL.md has 379 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~67
When it runs · the whole SKILL.md, loaded when a task matches
~1.5k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~2.7k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from wshobson/agents at commit 46891e7, republished under its MIT licence (© wshobson). 379 words, ~1,541 tokens.

Download SKILL.mdSave it as .claude/skills/python-error-handling/SKILL.md (or your agent's skills folder). This skill also uses 1 other file; get the full folder from GitHub.
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

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

python
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.

python
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.

python
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.

python
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 TypeExceptionExample
Invalid inputValueErrorBad parameter values
Wrong typeTypeErrorExpected string, got int
Missing itemKeyErrorDict key not found
Operational failureRuntimeErrorService unavailable
TimeoutTimeoutErrorOperation took too long
File not foundFileNotFoundErrorPath doesn't exist
Permission deniedPermissionErrorAccess forbidden
python
# 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")
Show full SKILL.md (128 more words)Show less

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

© wshobson, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 1 other file (references) in plugins/python-development/skills/python-error-handling of wshobson/agents.

  • SKILL.md
  • references/details.md

Open the folder on GitHubat commit 46891e7

Compare with similar skills

Python Error Handling next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Python Error Handling compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Python Error Handling this skillwshobson/agents40k—~1.5kAutomated safety check: PassMIT
Databricks Zerobus Ingestdatabricks/databricks-agent-skills345—~3.1kAutomated safety check: PassCustom licence
Cross-Language Coding Standardszereight/gitlab-mcp2k1 repos~1.4kAutomated safety check: PassMIT
Python Devdatabricks-solutions/ai-dev-kit1.9k—~1.6kAutomated safety check: PassCustom licence
Python Patternskurealnum/dotfiles2908 repos~4.1kAutomated safety check: PassNone
Python Script Runnercongchuanling-dot/Cohort199—~577Automated safety check: NotesMIT

Similar skills

  • Databricks Zerobus Ingest

    databricks/databricks-agent-skills

    Official

    Build Zerobus Ingest clients for near real-time data ingestion into Databricks Delta tables via gRPC.

    345 GitHub stars~3.1k tokensUpdated yesterday
    Backend & APIsAuto-check passed
  • Shared reference for naming, function size, complexity and error handling rules that reviewer agents apply across TypeScript, Python, Go, Rust, Java, C# and Swift.

    2k GitHub starsUsed in 1 repo~1.4k tokens
    DevelopmentAuto-check passed
  • Python Dev

    databricks-solutions/ai-dev-kit

    Python development guidance with code quality standards, error handling, testing practices, and environment management.

    1.9k GitHub stars~1.6k tokensUpdated 1 mo ago
    DevelopmentAuto-check passed
  • Python Patterns

    kurealnum/dotfiles

    Pythonic idioms, PEP 8 standards, type hints, and best practices for building robust, efficient, and maintainable Python applications.

    290 GitHub starsUsed in 8 repos~4.1k tokens
    DevelopmentAuto-check passed
  • Python Script Runner

    congchuanling-dot/Cohort

    Runs a Python script with checks first: confirms the interpreter version, compiles it for syntax errors, verifies imports, then explains any traceback in plain language.

    199 GitHub stars~577 tokensUpdated 1 mo ago
    DevelopmentAuto-check: notes
  • A skill your agent uses when writing shell scripts, Python automation, or any unattended batch job.

    3.5k GitHub stars~225 tokensUpdated 4 mo ago
    DevelopmentAuto-check passed

More from wshobson/agents

All 142 skills in this repo
  • Cuts cloud spend across AWS, Azure, GCP and OCI with cost tagging, rightsizing, commitment and spot pricing models, and architecture changes.

    40k GitHub starsUsed in 13 repos~1.7k tokens
    Auto-check passed
  • Billing Automation

    wshobson/agents

    Covers building subscription billing: billing cycles, subscription states, invoice generation, proration, tax handling and dunning for failed payments.

    40k GitHub starsUsed in 12 repos~473 tokens
    Auto-check passed
  • Profiles slow Python code with cProfile and memory profilers, then applies targeted fixes for CPU, memory, I/O and query bottlenecks.

    40k GitHub starsUsed in 12 repos~814 tokens
    Auto-check passed
  • Portfolio Risk Metrics

    wshobson/agents

    Covers portfolio risk measurement with VaR, CVaR, Sharpe, Sortino and drawdown, plus guidance on limits, stress tests and tail risk.

    40k GitHub starsUsed in 12 repos~502 tokens
    Auto-check passed
  • Plans memory headroom, works through out-of-memory failures and watches temperature and power during long ML training jobs on NVIDIA DGX Spark.

    40k GitHub starsUsed in 1 repo~2k tokens
    Auto-check passed
  • Writes unit tests for shell scripts with Bats: error-condition tests, fixtures and mocks, cross-shell checks, parallel runs, helper files and CI integration.

    40k GitHub starsUsed in 11 repos~1.3k tokens
    Auto-check passed

Works with

Categories

Questions about Python Error Handling

What does Python Error Handling do?

Python error handling patterns including input validation, exception hierarchies, and partial failure handling. Python Error Handling is an agent skill from wshobson/agents. Python error handling patterns including input validation, exception hierarchies, and partial failure handling.

When should I use Python Error Handling?

Python Error Handling fits situations like: implementing validation logic; designing exception strategies; handling batch processing failures; building robust APIs.

How do I install Python Error Handling in Claude Code?

Run `npx skills add wshobson/agents --skill python-error-handling -a claude-code`. Or copy the skill folder (plugins/python-development/skills/python-error-handling in wshobson/agents) into .claude/skills/python-error-handling in your project. Claude Code loads it when a task matches its description.

How do I install Python Error Handling in Codex?

Run `npx skills add wshobson/agents --skill python-error-handling -a codex`. Or copy the skill folder (plugins/python-development/skills/python-error-handling in wshobson/agents) into .agents/skills/python-error-handling in your project. Codex loads it when a task matches its description.

Can I use Python Error Handling in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add wshobson/agents --skill python-error-handling -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/python-error-handling, .gemini/skills/python-error-handling, .github/skills/python-error-handling and .opencode/skills/python-error-handling in your project.

What does Python Error Handling need to run?

SKILL.md names no scripts, command-line tools or credentials: Python Error Handling is instructions for the agent only. Our summary lists: Python 3.

Does Python Error Handling access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Python Error Handling safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Python Error Handling use?

Python Error Handling is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Python Error Handling use?

About 1.5k tokens (SKILL.md is roughly 6.2k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 1.2k tokens, read only when the agent opens those files.

What are the alternatives to Python Error Handling?

Skills that share tags, products or a category with Python Error Handling: Databricks Zerobus Ingest (databricks/databricks-agent-skills, 345 stars), Cross-Language Coding Standards (zereight/gitlab-mcp, 2k stars), Python Dev (databricks-solutions/ai-dev-kit, 1.9k stars) and Python Patterns (kurealnum/dotfiles, 290 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Python Error Handling?

wshobson (a GitHub user) maintains it in wshobson/agents, which has 40,254 GitHub stars. The repository holds 142 skills in this directory. The repository was last updated on October 5, 2026.

Source: wshobson/agents on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.