python - 如何捕获多线程的异常?

标签 python python-3.x multithreading exception python-multithreading

我有一组函数想在线程中执行。其中一些函数可能会引发我想为每个线程分别捕获的特定异常。

我尝试了一些类似的东西

import threading

class MyException(Exception):
    pass

def fun():
    raise MyException

myfuns = [threading.Thread(target=fun), threading.Thread(target=fun)]
for myfun in myfuns:
    try:
        myfun.start()
    except MyException:
        print("caught MyException")

我希望看到 caught MyException 两次,每个线程一个。但只有一个。

是否可以在线程中独立捕获异常? (换句话说:当线程引发异常时,在调用线程的代码中管理它?)

最佳答案

对于 Python 3.8+,您可以为未捕获的异常定义处理程序。

import threading

def f(args):
    print(f'caught {args.exc_type} with value {args.exc_value} in thread {args.thread}\n')
    
threading.excepthook = f

class MyException(Exception):
    pass

def fun():
    raise MyException

myfuns = [threading.Thread(target=fun), threading.Thread(target=fun)]
for myfun in myfuns:
    myfun.start()
for myfun in myfuns:
    myfun.join()

关于python - 如何捕获多线程的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64955599/

相关文章:

python - 安装 python 3.5 模块时出现问题

python - 我在 python 中解析数据文件时遇到 KeyError

python - 如何设置平滑过渡的 Windows 10 桌面背景?

java - JTextFields 在 JPanel 上的 Activity 绘图之上,线程问题

python - 使用 Python 从 Outlook 电子邮件正文中提取数字

python - 可以在 python 中创建没有日期的 datetime.date 对象吗?

python - 打印变量时 sys.stdout.write 和 print 的区别

image - 如何使用 tkinter/ttk 在 Python 3 中显示图像?

c - 简单的多线程,无需getch

java - 在另一个线程上有益地执行一件工作的最小尺寸?