如何处理Python线程中的异常?

如何处理Python线程中的异常?

给定代码重写以捕获异常

import sys
import threading
import time
import Queue
def thread(args1, stop_event, queue_obj):
print "开始线程"
stop_event.wait(12)
if not stop_event.is_set():
try:
raise Exception("出错了!")
except Exception:
queue_obj.put(sys.exc_info())
pass
try:
queue_obj = Queue.Queue()
t_stop = threading.Event()
t = threading.Thread(target=thread, args=(1, t_stop, queue_obj))
t.start()
time.sleep(15)
print "停止线程!"
t_stop.set()
try:
exc = queue_obj.get(block=False)
except Queue.Empty:
pass
else:
exc_type, exc_obj, exc_trace = exc
print exc_obj
except Exception as e:
print "用时太长了"
Python

输出:

C:/Users/TutorialsPoint1/~.py
开始线程
停止线程!
出错了!
Python

阅读更多:Python 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册