Install any skill in seconds. Free to start, no credit card required.
Get Started Free →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.
.claude/skills/dicklesworthstone-python-error-handling/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-02 | ✗→✓ | ▲ Improved | 63% | 0% |
| case-01 | ✓→✓ | = Same ✓ | 113% | 0% |
| case-03 | ✓→✓ | = Same ✓ | 229% | 0% |
| case-04 | ✓→✓ | = Same ✓ | 133% | 0% |
| case-05 | ✓→✓ | = Same ✓ | 142% | 0% |
Build robust Python applications with proper input validation, meaningful exceptions, and graceful failure handling. Good error handling makes debugging easier and systems more reliable.
Validate inputs early, before expensive operations. Report all validation errors at once when possible.
Use appropriate exception types with context. Messages should explain what failed, why, and how to fix it.
In batch operations, don't let one failure abort everything. Track successes and failures separately.
Chain exceptions to maintain the full error trail for debugging.
pythondef 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...
Validate all inputs at API boundaries before any processing begins.
pythondef 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)
Parse strings and external data into typed domain objects at system boundaries.
pythonfrom 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 ...
Use Pydantic models for structured input validation with automatic error messages.
pythonfrom 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())
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 |
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")
Create domain-specific exceptions that carry structured information.
pythonclass ApiError(Exception): """Base exception for API errors.""" def __init__( self, message: str, status_code: int, response_body: str | None = None, ) -> None: self.status_code = status_code self.response_body = response_body super().__init__(message) class RateLimitError(ApiError): """Raised when rate limit is exceeded.""" def __init__(self, retry_after: int) -> None: self.retry_after = retry_after super().__init__( f"Rate limit exceeded. Retry after {retry_after}s", status_code=429, ) # Usage def handle_response(response: Response) -> dict: match response.status_code: case 200: return response.json() case 401: raise ApiError("Invalid credentials", 401) case 404: raise ApiError(f"Resource not found: {response.url}", 404) case 429: retry_after = int(response.headers.get("Retry-After", 60)) raise RateLimitError(retry_after) case code if 400 <= code < 500: raise ApiError(f"Client error: {response.text}", code) case code if code >= 500: raise ApiError(f"Server error: {response.text}", code)
Preserve the original exception when re-raising to maintain the debug trail.
pythonimport httpx class ServiceError(Exception): """High-level service operation failed.""" pass def upload_file(path: str) -> str: """Upload file and return URL.""" try: with open(path, "rb") as f: response = httpx.post("https://upload.example.com", files={"file": f}) response.raise_for_status() return response.json()["url"] except FileNotFoundError as e: raise ServiceError(f"Upload failed: file not found at '{path}'") from e except httpx.HTTPStatusError as e: raise ServiceError( f"Upload failed: server returned {e.response.status_code}" ) from e except httpx.RequestError as e: raise ServiceError(f"Upload failed: network error") from e
Never let one bad item abort an entire batch. Track results per item.
pythonfrom dataclasses import dataclass @dataclass class BatchResult[T]: """Results from batch processing.""" succeeded: dict[int, T] # index -> result failed: dict[int, Exception] # index -> error @property def success_count(self) -> int: return len(self.succeeded) @property def failure_count(self) -> int: return len(self.failed) @property def all_succeeded(self) -> bool: return len(self.failed) == 0 def process_batch(items: list[Item]) -> BatchResult[ProcessedItem]: """Process items, capturing individual failures. Args: items: Items to process. Returns: BatchResult with succeeded and failed items by index. """ succeeded: dict[int, ProcessedItem] = {} failed: dict[int, Exception] = {} for idx, item in enumerate(items): try: result = process_single_item(item) succeeded[idx] = result except Exception as e: failed[idx] = e return BatchResult(succeeded=succeeded, failed=failed) # Caller handles partial results result = process_batch(items) if not result.all_succeeded: logger.warning( f"Batch completed with {result.failure_count} failures", failed_indices=list(result.failed.keys()), )
Provide visibility into batch progress without coupling business logic to UI.
pythonfrom collections.abc import Callable ProgressCallback = Callable[[int, int, str], None] # current, total, status def process_large_batch( items: list[Item], on_progress: ProgressCallback | None = None, ) -> BatchResult: """Process batch with optional progress reporting. Args: items: Items to process. on_progress: Optional callback receiving (current, total, status). """ total = len(items) succeeded = {} failed = {} for idx, item in enumerate(items): if on_progress: on_progress(idx, total, f"Processing {item.id}") try: succeeded[idx] = process_single_item(item) except Exception as e: failed[idx] = e if on_progress: on_progress(total, total, "Complete") return BatchResult(succeeded=succeeded, failed=failed)
ValueError, TypeError, not generic Exceptionraise ... from e to preserve debug info| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-01 | pass→pass | 10,513 | 22,552 | +115% | 1 | 1 | 0% | 2,043 | 4,355 | +113% | 0 | 0 | — |
case-02 | fail→pass | 13,292 | 7,244 | -46% | 1 | 1 | 0% | 2,500 | 4,064 | +63% | 0 | 0 | — |
case-03 | pass→pass | 5,985 | 5,035 | -16% | 1 | 1 | 0% | 1,130 | 3,715 | +229% | 0 | 0 | — |
case-04 | pass→pass | 8,873 | 6,108 | -31% | 1 | 1 | 0% | 1,659 | 3,871 | +133% | 0 | 0 | — |
case-05 | pass→pass | 11,919 | 13,339 | +12% | 1 | 1 | 0% | 2,224 | 5,371 | +142% | 0 | 0 | — |
case-06 | pass→pass | 9,870 | 7,755 | -21% | 1 | 1 | 0% | 1,466 | 4,224 | +188% | 0 | 0 | — |
case-07 | pass→pass | 14,103 | 13,307 | -6% | 1 | 1 | 0% | 2,650 | 5,292 | +100% | 0 | 0 | — |
case-08 | pass→pass | 13,606 | 15,494 | +14% | 1 | 1 | 0% | 2,490 | 5,795 | +133% | 0 | 0 | — |
case-09 | pass→pass | 6,593 | 8,000 | +21% | 1 | 1 | 0% | 1,081 | 4,247 | +293% | 0 | 0 | — |
case-10 | pass→pass | 11,196 | 11,439 | +2% | 1 | 1 | 0% | 2,219 | 4,928 | +122% | 0 | 0 | — |
case-11 | pass→pass | 6,745 | 5,935 | -12% | 1 | 1 | 0% | 1,323 | 3,668 | +177% | 0 | 0 | — |
case-12 | pass→pass | 18,023 | 13,605 | -25% | 1 | 1 | 0% | 3,179 | 5,141 | +62% | 0 | 0 | — |
case-13 | pass→pass | 5,305 | 6,123 | +15% | 1 | 1 | 0% | 974 | 3,947 | +305% | 0 | 0 | — |
case-14 | pass→pass | 11,902 | 8,158 | -31% | 1 | 1 | 0% | 2,079 | 4,147 | +99% | 0 | 0 | — |
case-15 | pass→pass | 7,837 | 8,840 | +13% | 1 | 1 | 0% | 1,253 | 4,497 | +259% | 0 | 0 | — |
case-16 | pass→pass | 11,444 | 8,294 | -28% | 1 | 1 | 0% | 2,012 | 4,242 | +111% | 0 | 0 | — |
case-17 | pass→pass | 13,173 | 13,160 | -0% | 1 | 1 | 0% | 2,135 | 5,241 | +145% | 0 | 0 | — |
case-18 | pass→pass | 6,082 | 8,842 | +45% | 1 | 1 | 0% | 1,198 | 4,428 | +270% | 0 | 0 | — |
case-19 | pass→pass | 4,958 | 4,617 | -7% | 1 | 1 | 0% | 907 | 3,520 | +288% | 0 | 0 | — |
case-20 | pass→pass | 3,608 | 4,966 | +38% | 1 | 1 | 0% | 553 | 3,551 | +542% | 0 | 0 | — |
case-21 | pass→pass | 4,113 | 3,886 | -6% | 1 | 1 | 0% | 832 | 3,363 | +304% | 0 | 0 | — |
case-22 | pass→pass | 10,253 | 17,790 | +74% | 1 | 1 | 0% | 2,079 | 5,580 | +168% | 0 | 0 | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 22 cases were attempted. The headline lift of +5 percentage points is the difference between those two pass rates over the 22 comparable cases.
Without the skill loaded, the model failed this case. With it loaded, the same prompt on the same model passed. This is one improved case from the latest verified run; every case, including any that regressed, is in the table above.
Other measured skills in the registry, with their headline benchmark lift.