Supprimer Rendre public Rendre privé Add tags Delete tags
  Ajouter un tag   Annuler
  Supprimer le tag   Annuler
  • • DevOps notes •
  •  
  • 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
  • Generics typing : Introduction to Generics Generic types let you write reusable, type-safe functions and classes that work uniformly across different data types. They ...
  • Python Modules and the import System : Python Modules and the import System What is a Module? A module in Python corresponds directly to a single file containing Python code. The module's ...
  • 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...
  • Working with JSON files : Working with JSON files JSON is the standard format for data exchange in web services and cloud APIs. Python’s built-in json module provides function...
  • Concise Iteration: List Comprehensions : Concise Iteration: List Comprehensions Simple for loops to create lists can be verbose. We can leverage list comprehensions to define the list content...


(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