Understanding Exception Handling in Python
This article provides a comprehensive guide to Python exception handling, covering the concept of exceptions, built‑in exception types, the try‑except‑else‑finally structure, custom exception creation, debugging techniques with assert and logging, and a practical file‑operation example to build robust programs.
Introduction
After learning Python basics such as syntax, functions, modules, and OOP, developers must handle errors and exceptions that inevitably occur in real‑world development. Exception handling is essential for writing robust programs that do not crash.
Exception Handling Overview
1. What is an Exception?
An exception is an error that occurs during program execution and interrupts the normal flow. Python provides many built‑in exception types (e.g., IndexError, KeyError, TypeError) that can be caught and handled.
2. Catching and Handling Exceptions
Python uses the try, except, else, and finally statements to manage exceptions. The basic structure is:
try:
# code that may raise an exception
except SomeError:
# handle the exception
else:
# execute if no exception occurred
finally:
# always executeExample:
try:
x = int(input("请输入一个整数: "))
result = 10 / x
except ValueError:
print("输入无效,请输入一个整数。")
except ZeroDivisionError:
print("不能除以0。")
else:
print(f"结果是: {result}")
finally:
print("程序结束。")Common Exception Types
Python defines many built‑in exceptions. The table below lists some frequently encountered ones:
Exception Type
Description IndexError Raised when accessing a non‑existent list or tuple index. KeyError Raised when accessing a missing dictionary key. TypeError Raised when an operation is applied to an inappropriate type. ValueError Raised when a function receives an argument of correct type but inappropriate value. ZeroDivisionError Raised when division by zero occurs. FileNotFoundError Raised when attempting to open a file that does not exist.
Example of handling an IndexError:
try:
my_list = [1, 2, 3]
print(my_list[5])
except IndexError as e:
print(f"发生异常:{e}")Custom Exceptions
Beyond built‑in types, developers can define their own exceptions by subclassing Exception:
class CustomError(Exception):
"""自定义异常类"""
pass
def divide(a, b):
if b == 0:
raise CustomError("除数不能为0")
return a / b
try:
result = divide(10, 0)
except CustomError as e:
print(f"捕获到自定义异常:{e}")Debugging and Logging
1. Using assert for Debugging
The assert statement checks a condition and raises AssertionError if the condition is false:
x = -1
assert x >= 0, "x 必须是非负数"2. Logging Errors
The logging module records runtime information, which aids debugging:
import logging
logging.basicConfig(filename='app.log', level=logging.ERROR)
try:
result = 10 / 0
except ZeroDivisionError as e:
logging.error(f"发生错误:{e}")Case Study: File Operations with Exception Handling
Below is a practical example that safely reads a file, handling missing‑file and I/O errors:
def read_file(filename):
try:
with open(filename, 'r') as file:
content = file.read()
return content
except FileNotFoundError:
print(f"文件 {filename} 不存在。")
except IOError:
print(f"读取文件 {filename} 时发生错误。")
# 测试读取文件
file_content = read_file("example.txt")
if file_content:
print(file_content)Conclusion
The article explored Python's exception handling mechanisms, including common exception types, the try‑except‑else‑finally flow, custom exception creation, and debugging techniques such as assertions and logging. Mastering these concepts enables developers to write more stable and reliable code.
Future articles will delve deeper into file operations and context managers.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
