面试题答案
一键面试Python多线程处理FileNotFoundError
异常
import threading
import time
def worker(file_path):
try:
with open(file_path, 'r') as f:
content = f.read()
print(f"线程 {threading.current_thread().name} 成功读取文件")
except FileNotFoundError:
global exception_count
lock.acquire()
exception_count += 1
lock.release()
exception_count = 0
lock = threading.Lock()
file_paths = ['nonexistent1.txt', 'nonexistent2.txt']
threads = []
for path in file_paths:
t = threading.Thread(target=worker, args=(path,))
threads.append(t)
t.start()
for t in threads:
t.join()
print(f"发生FileNotFoundError异常的线程数量: {exception_count}")
asyncio
处理ZeroDivisionError
异常
import asyncio
async def async_task(task_id):
try:
result = 1 / 0 if task_id == 2 else task_id * 2
print(f"任务 {task_id} 成功执行,结果: {result}")
except ZeroDivisionError as e:
global exception_info
exception_info.append(f"任务 {task_id} 发生异常: {str(e)}")
exception_info = []
async def main():
tasks = [async_task(i) for i in range(1, 4)]
await asyncio.gather(*tasks)
print("所有任务结束,异常信息汇总:")
for info in exception_info:
print(info)
if __name__ == "__main__":
asyncio.run(main())
以上代码中,多线程部分通过全局变量和锁来统计发生FileNotFoundError
异常的线程数量。异步编程部分使用asyncio
库,通过在每个异步任务中捕获ZeroDivisionError
异常,并将异常信息记录到全局列表中,最后在所有任务结束后展示异常信息。