Supprimer Rendre public Rendre privé Add tags Delete tags
  Ajouter un tag   Annuler
  Supprimer le tag   Annuler
  • • DevOps notes •
  •  
  • AI
  • Tags
  • Connexion

Signaling Errors: The raise Statement/shaare/ul6CvA

  • python
  • python

Signaling Errors: The raise Statement

  • Functions sometimes encounter states they cannot handle and must signal failure clearly.
  • Using raise triggers an exception, integrates with try...except, and stops execution immediately.
  • Prefer exceptions over special return values (None, False) to avoid ambiguous error handling.
  • Raising early enforces preconditions and supports the "fail fast" principle.
def process_servers(server_list):
    if not isinstance(server_list, list):
        # return None - BAD Practice, better to raise TypeError Exception
        raise TypeError("Input 'server_list' must be of type list.")

    # GOOD practice - Handle edge cases without raising exception
    if len(server_list) == 0:
        print("There are no servers to process. Exiting...")
        return

    print(f"Processing {len(server_list)} servers.")

# process_servers("abc") # Uncommenting will raise TypeError
process_servers([])
process_servers(["web01", "web02"])

Raising Built-in Exceptions

  • Built-in exception classes (e.g., TypeError, ValueError, FileNotFoundError) convey standard error semantics.
  • Raise TypeError when the argument’s type is wrong; raise ValueError when its value is out of acceptable range.
  • Use exceptions like OSError, ConnectionError, etc., when the built-in meaning matches your context.
  • Always include a clear, informative message describing the failure.
def set_deployment_replicas(count):
    """Example: enforce input type and value boundaries with built-in Exceptions."""
    try:
        parsed_count = int(count)
    except (ValueError, TypeError):
        raise TypeError(f"Replica count must be int or convertible to int, got {type(count).__name__}")

    if parsed_count < 0 or parsed_count > 100:
        raise ValueError(f"Replica count must be between 0 and 100")

    print(f"Replicas set to {parsed_count}")

for val in [5, -2, "three", 150, "5", 5.0]:
    try:
        set_deployment_replicas(val)
    except (TypeError, ValueError) as e:
        print(f"Caught error: {e}.")
2 months ago Permalien
cluster icon
  • Filesystem Paths : Working with Filesystem Paths in Python Manipulating paths as plain strings is error-prone and OS-specific. pathlib provides an object-oriented, cr...
  • The Iteration Protocol : The Iteration Protocol We use for item in sequence: all the time. But how does Python get each item? Iterable: An object that can be looped over. It...
  • Python Functions Are First‑Class Citizens : Python Functions Are First‑Class Citizens In Python, functions behave like any other object (strings, ints, lists). Because they are "first‑clas...
  • Automated Testing with Pytest : Assertions in Pytest Pytest uses Python’s built-in assert statement to declare expected conditions in tests, making test code concise and readable. W...
  • List : Lists (list) Lists are ordered, mutable sequences defined with square brackets []. You can add, remove, or change items after creation. Characteristic...


(110)
Filtrer par liens sans tag
Replier Replier tout Déplier Déplier tout Êtes-vous sûr de vouloir supprimer ce lien ? Êtes-vous sûr de vouloir supprimer ce tag ? Le gestionnaire de marque-pages personnel, minimaliste, et sans base de données par la communauté Shaarli