Topic 3 / 3📁 Unit Index
BP101T • Unit 4Topic 3 of 3⏱ 5 Min Read

3. Defensive Exception Handling (try-except-else-finally) for Lab Software

💡 Core Concept & Clinical Context:

In clinical dispensaries and hospital software, an unhandled runtime error (like typing text in a dose box or dividing by zero) could cause system crashes. Python's structured exception handling catches runtime errors gracefully, presents user-friendly error guidance, and ensures critical resources (like open database files) are safely closed.

Pharmaceutical Code & Calculation Examples:
1Robust Dispensary Dose Entry Validator

Using try-except-else-finally blocks to defensively handle faulty user inputs.

example_1.py
def safe_dose_entry():
    try:
        user_weight = float(input("Enter patient weight (kg): "))
        if user_weight <= 0:
            raise ValueError("Weight must be a positive number greater than 0.")
        
        target_mg_per_kg = float(input("Enter mg/kg prescribed: "))
        calculated_dose = user_weight * target_mg_per_kg
        
    except ValueError as ve:
        print(f"Validation Error: Invalid input value! Details: {ve}")
    except ZeroDivisionError:
        print("Arithmetic Error: Division by zero encountered.")
    else:
        # Executes ONLY if no exceptions were raised
        print(f"Validated Dose: {calculated_dose:.2f} mg safely calculated.")
    finally:
        # Executes UNCONDITIONALLY (ideal for logging/cleanup)
        print("Dispensary validation audit log completed.")
📋Key Takeaways & Exam Highlights
  • `try`: Contains code that could trigger runtime errors.
  • `except SpecificError`: Catches and handles known exceptions.
  • `else`: Executes only if the try block ran without exceptions.
  • `finally`: Executes unconditionally, regardless of whether an error occurred or was handled.
  • `raise ValueError(...)`: Manually throws custom exceptions when business rules are violated.
🇮🇳 हिन्दी व्याख्या (3. Defensive Exception Handling (try-except-else-finally) for Lab Software)

try-except का उपयोग इसलिए किया जाता है ताकि गलत इनपुट देने पर भी सॉफ्टवेयर क्रैश न हो, बल्कि सही एरर मैसेज देकर सिस्टम को सुरक्षित रखे।

Need to see the complete unit overview, solved numericals, or exam checklist?Open Unit 4 Overview Hub →