Learn Python try except finally, raise and logging for industrial automation scripts, SQL Server connectivity, report generation and production diagnostics.
Architecture: Exception Handling + Logging
Exception Handling + Logging
Program
Run automation/report code
main()TRY
Execute expected operation
try:Exception
Catch known failures
except pyodbc.Error:Logging
Record event and context
logger.exception(...)FINALLY
Release resources
finally:Recovery
Exit, retry or notify
raise / return1. Why exception handling matters
A production report should distinguish connection failures, invalid input, file permission errors and unexpected faults instead of stopping without useful diagnostics.
2. Basic try / except
try: value = float("850.25") print(value)
except ValueError as error: print("Invalid number:", error)3. else and finally
connection = None
try: connection = connect_to_sql()
except Exception as error: print("Connection failed:", error)
else: print("Connection successful")
finally: if connection is not None: connection.close()4. Raise your own validation error
def validate_sqf_no(value): if value not in {1, 2, 3}: raise ValueError("SQF_No must be 1, 2 or 3") return value5. Use the Standard Library logging module
import logging logging.basicConfig( filename="sqf_report.log", level=logging.INFO, format="%(asctime)s | %(levelname)s | %(message)s",
) logging.info("Report program started")
logging.warning("No records returned")6. Log full exception details
try: 1 / 0
except Exception: logging.exception("Unexpected report failure")logging.exception() records the traceback when called inside an exception handler.
Frequently Asked Questions
What is the difference between except and finally?
except handles matching exceptions; finally runs whether the protected block succeeds or fails.
Why use logging instead of only print?
Logging adds timestamps, severity levels and persistent diagnostic history that is useful for production support.
What does raise do?
raise creates or re-throws an exception so invalid or failed conditions are not silently ignored.
