3. Defensive Exception Handling (try-except-else-finally) for Lab Software
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.
Using try-except-else-finally blocks to defensively handle faulty user inputs.
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.")- `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.
try-except का उपयोग इसलिए किया जाता है ताकि गलत इनपुट देने पर भी सॉफ्टवेयर क्रैश न हो, बल्कि सही एरर मैसेज देकर सिस्टम को सुरक्षित रखे।