Python · Industrial Automation

Python Exception Handling & Logging for Industrial Automation

Learn Python try except finally, raise and logging for industrial automation scripts, SQL Server connectivity, report generation and production diagnostics.

Practical Python Automation Context Copy-Paste Examples Code Architecture

Learning Overview

Python Learning SeriesPython for Industrial AutomationPractical

Learning Goal

  • Learn Python try except finally, raise and logging for industrial automation scripts, SQL Server connectivity, report generation and production diagnostics.
  • Run the examples in VS Code using the project environment prepared in earlier topics.
  • Understand where this topic fits in the complete SQL, reporting and Industry 4.0 workflow.
Quick answer

Learn Python try except finally, raise and logging for industrial automation scripts, SQL Server connectivity, report generation and production diagnostics.

Architecture: Exception Handling + Logging

Code-Based Architecture

Exception Handling + Logging

1

Program

Run automation/report code

main()
2

TRY

Execute expected operation

try:
3

Exception

Catch known failures

except pyodbc.Error:
4

Logging

Record event and context

logger.exception(...)
5

FINALLY

Release resources

finally:
6

Recovery

Exit, retry or notify

raise / return
ProgramTRYExceptionLoggingFINALLYRecovery

1. 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 value

5. 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.

Reviewed by Bhawesh Kumar SinghIndustrial Automation Trainer and Industry 4.0 Consultant · Softwell Automation · 21+ years industry experience
Complete Python for Industrial Automation Learning Path

Use Previous / Next for sequential training, or open any topic directly.

Complete

Continue with the next topic in the Python for Industrial Automation learning path.

Open Learning Path
Python for Industrial Automation

Exception Handling + Logging

Learn Python try except finally, raise and logging for industrial automation scripts, SQL Server connectivity, report generation and production diagnostics.

Content reviewed: 14 September 2026

☎ Call WhatsApp ✉ Email Enquire Now