MST

星途 面试题库

面试题:Python异常处理在多线程与异步编程中的应用

在一个Python多线程程序中,每个线程执行一个函数`worker`,`worker`函数会进行一些文件读写操作。如果在文件读取时发生`FileNotFoundError`异常,需要在主线程中捕获这个异常,并统计发生异常的线程数量。另外,在一个异步编程(使用`asyncio`库)的场景下,有多个异步任务`async_task`,当某个异步任务中发生`ZeroDivisionError`异常时,如何优雅地处理这个异常,保证其他异步任务不受影响,同时记录下发生异常的任务信息,并在所有任务结束后,将异常信息汇总展示。
42.3万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试

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异常,并将异常信息记录到全局列表中,最后在所有任务结束后展示异常信息。