Handling Errors in Python Functions

Writing Functions Mar 16, 2026

Handling Errors in Python Functions – Best Practices 2026

Proper error handling is one of the most important aspects of writing robust and maintainable Python functions. In 2026, following modern error handling practices helps create reliable code that gracefully handles unexpected situations.

TL;DR — Key Best Practices 2026

  • Use specific exceptions instead of bare except:
  • Keep error handling close to where the error can occur
  • Use custom exception classes for domain-specific errors
  • Provide clear, actionable error messages
  • Always clean up resources using context managers

1. Basic Error Handling


def divide(a: float, b: float) -> float:
    """Divide two numbers with proper error handling."""
    if b == 0:
        raise ValueError("Cannot divide by zero")
    return a / b

# Good usage
try:
    result = divide(10, 0)
except ValueError as e:
    print(f"Error: {e}")

2. Modern Best Practices


from typing import Optional

class InvalidUserInputError(Exception):
    """Custom exception for invalid user input."""
    pass

def process_user_input(value: str) -> Optional[int]:
    """Process user input with clear error handling."""
    try:
        number = int(value)
        if number < 0:
            raise InvalidUserInputError("Number must be non-negative")
        return number
    except ValueError:
        raise InvalidUserInputError(f"Invalid number format: {value}") from None
    except Exception as e:
        # Log unexpected errors but don't expose details to user
        logger.error(f"Unexpected error processing input: {e}")
        raise RuntimeError("An unexpected error occurred") from e

3. Best Practices for Error Handling in Functions (2026)

  • Use specific exceptions rather than catching everything with bare except:
  • Create custom exception classes for your domain logic
  • Provide clear, user-friendly error messages
  • Use context managers to ensure resources are always cleaned up
  • Log unexpected errors but don’t expose internal details to users
  • Use raise ... from None to suppress unnecessary traceback when re-raising

Conclusion

Good error handling is not just about catching exceptions — it’s about writing functions that fail gracefully, provide useful feedback, and maintain system stability. In 2026, following these best practices leads to more reliable, maintainable, and professional Python code.

Next steps:

Share:
Last updated: March 2026
Built-in Functions in Python 2026 str() in Python 2026: String Conversion + Modern Formatting & Best Practices memoryview with JAX in Python 2026: Zero-Copy NumPy → JAX Array Interop + Efficient ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + GPU Pinning & ML Examples memoryview with TensorFlow in Python 2026: Zero-Copy NumPy → Tensor Interop + ML Examples memoryview with NumPy & PyTorch in Python 2026: Zero-Copy Views, Efficient Slicing & ML Interop Examples memoryview with NumPy in Python 2026: Zero-Copy Views, Efficient Slicing & Real ML Examples memoryview() in Python 2026: Zero-Copy Magic for Large Binary Data + Real Examples import() in Python 2026: How It Works, Security Risks & Modern Alternatives (importlib) zip() in Python 2026: How to Use It, strict=True Behavior & Real-World Examples vars() in Python 2026: Accessing Object Namespace + Modern Introspection Patterns type() in Python 2026: Dynamic Type Inspection & Object Creation + Modern Patterns tuple() in Python 2026: Immutable Sequences + Modern Patterns & Best Practices super() in Python 2026: Method Resolution & Modern Inheritance Patterns sum() in Python 2026: Summing Iterables + Modern Numeric Patterns & Best Practices staticmethod() in Python 2026: Static Methods, Utility Functions & Modern Best Practices sorted() in Python 2026: Sorting Iterables + Modern Patterns & Best Practices slice() in Python 2026: Creating Slice Objects + Modern Patterns & Best Practices setattr() in Python 2026: Dynamic Attribute Setting + Modern Patterns & Safety set() in Python 2026: Mutable Sets Creation + Modern Patterns & Best Practices