English translation
9. Exception Handling in Python for App Automation
AI Article Decision Snapshot
Turn the lesson into workflow, model, budget, and security checks before choosing tools.
Use this quick snapshot before leaving the article. It keeps the next search tied to practical AI software, model/API, cost, privacy, and implementation questions.
Workflow fit
Identify the real job behind the article: coding, research, document review, support, analytics, content, or internal automation.
Model or tool decision
Decide whether the next step is a software shortlist, an AI tool comparison, an API platform choice, or a model benchmark.
Budget and usage signal
Estimate seats, API calls, prompt volume, retries, review time, and fallback work before assuming the workflow is cheap.
Security and privacy review
Check whether source code, customer data, private documents, prompts, logs, or embeddings will enter the AI workflow.
In the previous article, we introduced commonly used modules that will play a critical role in our automation tasks. However, exception handling is an essential topic in any program development. This article delves into how to implement robust exception handling in Python—ensuring the stability and reliability of our automation scripts during execution.
What Is an Exception?
During program execution, unexpected situations may arise—for example, missing files, network connectivity issues, or type mismatches. Such situations are called exceptions. When an exception occurs, the normal flow of execution is interrupted. Therefore, we need exception-handling mechanisms to catch and respond to these exceptions appropriately.
Basic Exception Handling in Python
In Python, we use the try, except, else, and finally statement blocks for exception handling. The basic structure is as follows:
try:
# Code that might raise an exception
except ExceptionType:
# Code to handle the exception
else:
# Code executed only if no exception occurred
finally:
# Code always executed, regardless of whether an exception occurred
1. The try Statement
Place code that may raise an exception inside the try block. If the code executes successfully, the program continues normally; if an exception occurs, control transfers to the corresponding except block.
2. The except Statement
The except block lets you specify the exact exception type(s) to catch. For example:
try:
num = int(input("Please enter a number: "))
except ValueError:
print("Invalid input! Please enter a valid integer.")
Here, if the user enters something that cannot be converted to an integer, the program catches the ValueError and displays an appropriate error message.
3. The else Statement
The else block contains code that runs only when no exception occurs in the try block. Example:
try:
num = int(input("Please enter a number: "))
except ValueError:
print("Invalid input! Please enter a valid integer.")
else:
print(f"The number you entered is: {num}")
In this case, the success message prints only when the user provides valid numeric input.
4. The finally Statement
Code in the finally block always executes—whether or not an exception occurred—making it ideal for cleanup tasks (e.g., closing files or releasing resources). Example:
file = None
try:
file = open('example.txt', 'r')
# Perform file operations
except FileNotFoundError:
print("File not found!")
finally:
if file:
file.close() # Ensure the file is closed
Catching Multiple Exceptions
You can catch multiple exception types in a single except block—or use separate except blocks to handle different exception types individually.
Example:
try:
result = 10 / int(input("Please enter a divisor: "))
except ValueError:
print("Invalid input! Please enter a valid number.")
except ZeroDivisionError:
print("Error! Division by zero is not allowed.")
else:
print(f"Result: {result}")
This example handles both invalid input and division-by-zero errors effectively.
Custom Exceptions
Beyond built-in exceptions, Python allows you to define your own custom exception classes—enabling precise, project-specific error reporting.
Example:
class MyCustomError(Exception):
pass
def do_something(value):
if value < 0:
raise MyCustomError("Input value cannot be negative!")
return value ** 2
try:
result = do_something(-5)
except MyCustomError as e:
print(e)
In this example, passing a negative value to do_something() triggers the custom exception, which is then caught and printed.
Summary
Robust exception handling is foundational to building reliable Python automation scripts. By thoughtfully applying try, except, else, and finally, we can gracefully manage runtime errors—ensuring our automation workflows execute smoothly and predictably.
Next, we’ll explore “Automation with Python: Interfacing Python with the Operating System”, laying the groundwork for deeper software automation capabilities. In that article, you’ll learn how Python interacts with the operating system—enhancing both the efficiency and flexibility of your automation solutions.
Apply This Lesson
Turn this article into AI software, model, API, and security decisions.
English Article FAQ
Use this article as evidence before choosing AI tools
How should I use this AI Tutorials article?
Use it as the implementation or learning layer, then connect the idea to AI software buyer guides, tool comparisons, benchmarks, API choices, and security checks before making a production decision.
Is this English article different from the Chinese original?
The English edition is localized for global AI readers while preserving the original diagrams, screenshots, prompts, code examples, and source context from the Chinese article.
What should I read after 9. Exception Handling in Python for App Automation?
Continue with AI Software Buyer Guides, AI Tools Workbench, Best AI Coding Agents, AI Model Benchmarks, OpenAI vs Anthropic API, or LLM Security Tools depending on the decision you need to make.
Can this article alone choose an AI product or model?
No. Treat the article as evidence and context, then validate fit with pricing, privacy requirements, integration effort, benchmark results, workflow tests, and fallback planning.
Continue