Chapter 9: Exception Handling & Debugging
Manage errors and troubleshoot automation workflows. Develop reliable automation systems with logging, recovery, screenshots, retries and debugging techniques.
Errors
Details
Safely
Reliability
9.1 Chapter Overview
Automation bots must work reliably in real business environments. However, automation can fail because of missing files, changed web pages, slow applications, invalid data, connection problems, locked Excel files or unexpected popups.
Exception handling and debugging are essential skills for building reliable automation systems. A good automation bot should not crash silently. It should detect errors, record useful logs, take screenshots where needed, recover safely and notify users when human action is required.
9.2 Learning Objectives
- Understand common automation errors and failure points.
- Use Python try, except, else and finally blocks.
- Create error logs for automation workflows.
- Take screenshots during automation failures.
- Debug Python automation scripts using print, logging and breakpoints.
- Use retries for temporary failures.
- Handle Selenium and web automation exceptions.
- Design reliable automation workflows with recovery and notification steps.
9.3 Common Automation Errors
| Error Type | Cause | Example |
|---|---|---|
| FileNotFoundError | Required file does not exist. | Excel file is missing. |
| PermissionError | File is open or locked. | Bot tries to overwrite an open Excel file. |
| ValueError | Invalid data format. | Text entered where number is expected. |
| NoSuchElementException | Web element cannot be found. | Website button ID changed. |
| TimeoutException | Page or element loads too slowly. | Web portal is slow. |
| Connection Error | Network or server unavailable. | API or website cannot be reached. |
9.4 Basic Exception Handling with try-except
The try-except block allows a program to continue or respond properly when an error occurs.
try:
number = int(input("Enter a number: "))
result = 100 / number
print("Result:", result)
except ValueError:
print("Please enter a valid number.")
except ZeroDivisionError:
print("Number cannot be zero.")Line-by-Line Explanation
| Code | Explanation |
|---|---|
| try: | Runs code that may cause an error. |
| except ValueError: | Handles invalid number conversion. |
| except ZeroDivisionError: | Handles division by zero. |
9.5 try-except-else-finally
Python provides else and finally blocks for better workflow control.
try:
file = open("pdtc_report.txt", "r", encoding="utf-8")
content = file.read()
except FileNotFoundError:
print("Report file not found.")
else:
print("File read successfully.")
print(content)
finally:
print("Automation step completed.")| Block | Purpose |
|---|---|
| try | Code that may fail. |
| except | Runs when an error occurs. |
| else | Runs only if no error occurs. |
| finally | Runs whether error occurs or not. |
9.6 File Error Handling Example
This example checks whether an input Excel file exists before running an automation report.
from pathlib import Path
import pandas as pd
input_file = Path("business_transactions.xlsx")
try:
if not input_file.exists():
raise FileNotFoundError("Input Excel file is missing.")
df = pd.read_excel(input_file)
print("Excel file loaded successfully.")
print(df.head())
except FileNotFoundError as error:
print("Automation stopped:", error)
except Exception as error:
print("Unexpected error:", error)9.7 Logging Automation Activity
Logging records what the bot is doing. It helps troubleshoot failures and creates an audit trail.
import logging
logging.basicConfig(
filename="automation_log.txt",
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
logging.info("Automation started")
try:
total = 100 / 5
logging.info("Calculation completed successfully")
except Exception as error:
logging.error("Automation failed: %s", error)
logging.info("Automation finished")Log Levels
| Level | Use |
|---|---|
| DEBUG | Detailed troubleshooting information. |
| INFO | Normal process updates. |
| WARNING | Something unexpected but not critical. |
| ERROR | Step failed. |
| CRITICAL | Serious failure requiring immediate action. |
9.8 Screenshot on Error
For desktop and web automation, screenshots help identify what happened at the time of failure.
Desktop Screenshot with PyAutoGUI
import pyautogui
from datetime import datetime
try:
raise Exception("Sample automation failure")
except Exception as error:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
screenshot_file = "error_screenshot_" + timestamp + ".png"
pyautogui.screenshot().save(screenshot_file)
print("Error:", error)
print("Screenshot saved:", screenshot_file)Web Screenshot with Selenium
from selenium import webdriver
from datetime import datetime
driver = webdriver.Chrome()
try:
driver.get("https://example.com")
raise Exception("Sample web automation error")
except Exception as error:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
driver.save_screenshot("web_error_" + timestamp + ".png")
print("Error screenshot captured.")
finally:
driver.quit()9.9 Debugging Automation Scripts
Debugging means finding and fixing problems in code or workflow logic.
Print Debugging
Print variable values and step status.
Logging
Record process flow in a log file.
Breakpoints
Pause code in IDE to inspect values.
Screenshots
Capture application state when failure occurs.
Print Debugging Example
amount = "1200"
print("Before conversion:", amount)
amount = float(amount)
print("After conversion:", amount)Using breakpoint()
department = "Finance" amount = 1200 breakpoint() total = amount * 1.06 print(department, total)
9.10 Retry Logic for Temporary Failures
Some failures are temporary, such as slow internet, delayed page loading or locked files. Retry logic allows the bot to try again before failing.
import time
def unreliable_step():
print("Trying automation step...")
# Replace this with real automation logic.
raise Exception("Temporary failure")
max_attempts = 3
for attempt in range(1, max_attempts + 1):
try:
unreliable_step()
print("Step completed successfully.")
break
except Exception as error:
print("Attempt", attempt, "failed:", error)
if attempt == max_attempts:
print("Maximum attempts reached. Escalate to human user.")
else:
time.sleep(2)9.11 Reliable Bot Design Pattern
9.12 Selenium Exception Handling
Web automation commonly fails when elements are missing, pages load slowly, or selectors change.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException, TimeoutException
driver = webdriver.Chrome()
try:
driver.get("https://example.com")
button = driver.find_element(By.ID, "submitBtn")
button.click()
except NoSuchElementException:
print("Button not found. Check element ID or page structure.")
driver.save_screenshot("missing_element.png")
except TimeoutException:
print("Page took too long to load.")
finally:
driver.quit()9.13 Validation Before Automation
Validation prevents many errors before the bot starts processing.
import pandas as pd
from pathlib import Path
required_columns = ["Date", "Department", "Amount", "Status"]
file_path = Path("business_transactions.xlsx")
try:
if not file_path.exists():
raise FileNotFoundError("Excel file does not exist.")
df = pd.read_excel(file_path)
missing = [col for col in required_columns if col not in df.columns]
if missing:
raise ValueError("Missing columns: " + str(missing))
print("Validation successful. Bot can continue.")
except Exception as error:
print("Validation failed:", error)9.14 Creating an Error Report
A bot can save failed records into an error report for human review.
import pandas as pd
data = {
"Name": ["Amin", "Mei Ling", "Ravi"],
"Amount": [1200, -50, None]
}
df = pd.DataFrame(data)
errors = df[(df["Amount"].isna()) | (df["Amount"] <= 0)]
errors.to_excel("automation_error_report.xlsx", index=False)
print("Error report created.")9.15 Interactive Error Handling Simulator
This simple simulator shows how validation can catch common input errors.
9.16 Troubleshooting Checklist
| Question | Purpose |
|---|---|
| Is the input file available? | Prevents FileNotFoundError. |
| Are required columns present? | Prevents data processing errors. |
| Is the application open and ready? | Prevents click/type failures. |
| Did the web page load completely? | Prevents missing element errors. |
| Are selectors still valid? | Prevents Selenium failures. |
| Is the file locked by another user? | Prevents permission errors. |
| Are logs and screenshots available? | Supports troubleshooting. |
9.17 Practical Activities
Activity 1: Basic Error Handling
Write a Python script that asks for a number and handles invalid input and division by zero.
Activity 2: File Validation
Create a script that checks whether an Excel file exists before reading it.
Activity 3: Logging
Create an automation_log.txt file and write start, success and error messages.
Activity 4: Error Screenshot
Use PyAutoGUI or Selenium to capture a screenshot when an error occurs.
Mini Project
Improve your Chapter 8 reporting bot by adding validation, logging, try-except blocks and an error report.
9.18 Interactive Final Assessment Quiz
Each correct answer gives +1 mark.
Each wrong answer gives -0.5 mark.
1. Exception handling helps automation bots manage errors.
2. Which Python block handles errors?
3. Logging helps create an audit trail for automation.
4. FileNotFoundError may occur when a required file is missing.
5. Screenshots can help troubleshoot automation failures.
6. Which log level usually records serious failure?
7. Retry logic can help with temporary failures.
8. Validation should happen after the bot has already failed only.
9. NoSuchElementException is common in Selenium when an element cannot be found.
10. Reliable automation systems should include logging, validation and recovery steps.
Your Score: 0
9.19 Chapter Summary
In this chapter, learners studied exception handling, debugging, logging, screenshots on error, validation, retry logic, Selenium exception handling and reliable bot design. These skills help develop automation systems that can survive real-world failures.