Fundamental and Advanced Exception Handling in Python
This article presents a comprehensive guide to Python exception handling, covering basic try‑except usage, multiple exception capture, else/finally clauses, custom exceptions, exception chaining, logging, context managers, assertions, traceback, concurrent and asynchronous error handling, and testing techniques.
Basic Exception Handling
1. Simple try‑except to catch errors such as division by zero.
try:
result = 10 / 0
except ZeroDivisionError:
print("不能除以零")2. Capturing multiple exceptions in one block.
try:
num = int(input("请输入一个整数: "))
result = 10 / num
except (ValueError, ZeroDivisionError):
print("输入无效或不能除以零")3. Using an else clause to run code when no exception occurs.
try:
num = int(input("请输入一个整数: "))
result = 10 / num
except (ValueError, ZeroDivisionError):
print("输入无效或不能除以零")
else:
print(f"结果是: {result}")4. Using a finally clause for cleanup actions.
try:
file = open("example.txt", "r")
content = file.read()
except FileNotFoundError:
print("文件未找到")
finally:
file.close()
print("文件已关闭")Advanced Exception Handling
5. Accessing exception information.
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"发生异常: {e}")6. Defining custom exception classes.
class CustomError(Exception):
pass
def check_value(x):
if x < 0:
raise CustomError("值不能为负数")
try:
check_value(-1)
except CustomError as e:
print(f"自定义异常: {e}")7. Exception chaining with raise ... from .
try:
1 / 0
except ZeroDivisionError as e:
raise ValueError("计算错误") from e8. Logging exceptions to a file.
import logging
logging.basicConfig(filename='app.log', level=logging.ERROR)
try:
1 / 0
except ZeroDivisionError as e:
logging.error(f"发生异常: {e}")Complex Exception Handling
9. Nested try‑except structures.
try:
try:
result = 10 / 0
except ZeroDivisionError:
print("内层异常: 不能除以零")
raise
except ZeroDivisionError:
print("外层异常: 不能除以零")10. Handling exceptions inside loops.
numbers = [1, 0, 2, 'a']
for num in numbers:
try:
print(10 / num)
except (ZeroDivisionError, TypeError) as e:
print(f"异常: {e}")11. Using a context manager for resource handling.
from contextlib import contextmanager
@contextmanager
def managed_resource(*args, **kwds):
resource = open(*args, **kwds)
try:
yield resource
finally:
resource.close()
with managed_resource("example.txt", "r") as f:
content = f.read()
print(content)12. Assertions for development checks.
def divide(a, b):
assert b != 0, "除数不能为零"
return a / b
try:
result = divide(10, 0)
except AssertionError as e:
print(f"断言失败: {e}")Advanced Topics
13. Using traceback to print full stack traces.
import traceback
try:
1 / 0
except ZeroDivisionError:
traceback.print_exc()14. Accessing exception details with sys.exc_info .
import sys
try:
1 / 0
except ZeroDivisionError:
exc_type, exc_value, exc_traceback = sys.exc_info()
print(f"异常类型: {exc_type}")
print(f"异常值: {exc_value}")
print(f"堆栈跟踪: {exc_traceback}")15. Emitting warnings instead of raising exceptions.
import warnings
def some_function():
warnings.warn("这是一个警告信息", UserWarning)
try:
some_function()
except UserWarning as w:
print(f"警告: {w}")16. Suppressing specific exceptions with contextlib.suppress .
from contextlib import suppress
with suppress(FileNotFoundError):
with open("nonexistent_file.txt", "r") as f:
content = f.read()
print(content)17. Unit testing exception behavior.
import unittest
class TestExceptions(unittest.TestCase):
def test_divide_by_zero(self):
with self.assertRaises(ZeroDivisionError):
1 / 0
if __name__ == '__main__':
unittest.main()18. Handling exceptions in threads using concurrent.futures .
import concurrent.futures
def divide(a, b):
return a / b
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(divide, 10, 0)
try:
result = future.result()
except ZeroDivisionError as e:
print(f"线程异常: {e}")19. Managing asynchronous exceptions with asyncio .
import asyncio
async def divide(a, b):
await asyncio.sleep(1)
return a / b
async def main():
try:
result = await divide(10, 0)
except ZeroDivisionError as e:
print(f"异步异常: {e}")
asyncio.run(main())20. Handling system signals using the signal module.
import signal
import time
def handle_signal(signum, frame):
print("接收到信号:", signum)
signal.signal(signal.SIGINT, handle_signal)
while True:
time.sleep(1)
print("运行中...")Summary
These examples cover exception handling from simple try‑except statements to complex scenarios involving multithreading, asynchronous programming, logging, testing, and system signals, providing a solid foundation for writing robust Python code.
Test Development Learning Exchange
Test Development Learning Exchange
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.