Chapter 9: Exception Handling & Debugging

Manage errors and troubleshoot automation workflows. Develop reliable automation systems with logging, recovery, screenshots, retries and debugging techniques.

Error HandlingDebuggingLoggingRetriesReliable Bots
Detect
Errors
Log
Details
Recover
Safely
Improve
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.

Learning Outcome: By the end of this chapter, learners should be able to manage errors, troubleshoot automation workflows and develop reliable automation systems.
Run Bot
Detect Error
Log Details
Retry / Recover
Report Status

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 TypeCauseExample
FileNotFoundErrorRequired file does not exist.Excel file is missing.
PermissionErrorFile is open or locked.Bot tries to overwrite an open Excel file.
ValueErrorInvalid data format.Text entered where number is expected.
NoSuchElementExceptionWeb element cannot be found.Website button ID changed.
TimeoutExceptionPage or element loads too slowly.Web portal is slow.
Connection ErrorNetwork or server unavailable.API or website cannot be reached.
Important: A reliable bot must expect errors and handle them properly instead of stopping unexpectedly.

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

CodeExplanation
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.")
BlockPurpose
tryCode that may fail.
exceptRuns when an error occurs.
elseRuns only if no error occurs.
finallyRuns 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)
Good Practice: Check required files before starting a long automation workflow.

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

LevelUse
DEBUGDetailed troubleshooting information.
INFONormal process updates.
WARNINGSomething unexpected but not critical.
ERRORStep failed.
CRITICALSerious 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)
Note: breakpoint() pauses code execution so you can inspect variables in the terminal or IDE.

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

1Validate Inputs
2Start Logging
3Run Step
4Handle Error
5Retry if Needed
6Report Result
Reliable Automation = Validation + Logging + Exception Handling + Recovery + Reporting

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.

Click Run Validation.

9.16 Troubleshooting Checklist

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

Remember: A professional automation bot does not only work when everything is perfect. It also handles failure safely and gives clear information for troubleshooting.