Python Error Handling

作者 wshobson46891e7e60da無授權條款收錄於 2026年10月8日更新於 2026年10月8日

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.

AI 產生的概覽

指導 Python 錯誤處理:輸入驗證、例外階層與部分失敗處理。

功能
此技能提供建構穩健 Python 應用程式並妥善處理錯誤的指引與程式碼模式。內容涵蓋快速失敗的輸入驗證、將外部資料轉換為具型別的領域物件、使用 Pydantic 模型進行結構化驗證、將失敗對應到標準內建例外,以及在批次操作中處理部分失敗。它產出的是說明性模式、程式碼範例與最佳實務清單,而非可執行指令碼。
適用情境
適用於實作驗證邏輯、設計例外階層、處理批次失敗或建構穩健 API 的情境。在將外部資料轉換為領域型別或撰寫使用者友善的錯誤訊息時同樣適用。
執行需求
除代理程式外無需指令碼或執行階段相依性;此技能僅為說明性內容。範例涉及 Python 與 Pydantic 程式庫,更多細節位於 references/details.md。

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 boundarydef 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()
# Usagetry:    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 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 contextraise ValueError(f"'page_size' must be 1-100, got {page_size}")
# Avoid: Generic exception, no contextraise 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

來源與署名

來源:wshobson/agents位於plugins/python-development/skills/python-error-handling提交46891e7

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架