Chapter 9: Writing Robust Scripts with Functions and Error Handling
So far, our scripts have been single, continuous blocks of code. This works well for simple tasks, but as your automation projects grow in complexity, it's essential to write code that is organized, reusable, and can handle unexpected issues without crashing.
In this chapter, you will learn two fundamental concepts of professional programming:
Functions: How to group your code into logical, reusable blocks.
Error Handling: How to anticipate and manage common errors, like a missing file.
We will refactor the sales report script from Chapter 7 to make it more robust.
The Power of Functions
A function is a named block of code that performs a specific task. Using functions makes your code cleaner, easier to read, and allows you to reuse code without copying and pasting.
Let's break our sales report script into three main tasks, each becoming a function:
load_data_from_csv(): Reads the raw sales data.process_and_format_sheet(): Adds formulas and styles to the data.create_summary_chart(): Creates the sales chart on a new sheet.
Handling Errors with try...except
try...exceptWhat happens if our script runs, but the sales_data.csv file isn't there? The script will crash with a FileNotFoundError. A more professional approach is to "catch" this error and show a friendly message. We can do this using a try...except block.
The logic is simple:
try: Python attempts to run the code inside this block.except: If an error occurs in thetryblock, the code inside theexceptblock is executed instead of crashing the program.
The Refactored Script: robust_sales_report.py
robust_sales_report.pyHere is the new, improved version of our script. It performs the exact same task as the one in Chapter 7, but it's much better organized and can handle a missing input file. Create a file named robust_sales_report.py.
Now, try running the script twice. First, with the sales_data.csv file present. It will work as before. Then, rename sales_data.csv to something else and run the script again. This time, it won't crash. It will print a clear error message and stop gracefully.
What You've Accomplished
You have made a significant leap from being a scripter to becoming a programmer. You can now write automation scripts that are not just functional but also well-organized, easy to debug, and resilient to common real-world problems. These skills are essential for building reliable and maintainable automation solutions.
Last updated