共計 913 個字符,預計需要花費 3 分鐘才能閱讀完成。
Python 線程捕獲不到異常的原因是因為線程中的異常默認是不會被拋出到主線程的。
解決這個問題,可以使用 try/except 語句在線程內部捕獲異常,并將異常信息傳遞給主線程。可以通過以下幾種方式實現:
- 使用全局變量傳遞異常信息:在線程內部捕獲異常,并將異常信息賦值給一個全局變量,主線程可以通過檢查這個全局變量來獲取異常信息。
import threading
# 全局變量用于保存異常信息
global_exception = None
def thread_function():
global global_exception
try:
# 線程邏輯
pass
except Exception as e:
global_exception = e
# 創建線程
thread = threading.Thread(target=thread_function)
# 啟動線程
thread.start()
# 等待線程結束
thread.join()
# 檢查異常信息
if global_exception:
print("Thread exception:", global_exception)
- 使用線程間通信隊列:創建一個隊列,線程內部捕獲異常后,將異常信息放入隊列中,主線程可以從隊列中獲取異常信息。
import threading
import queue
# 創建隊列用于線程間通信
exception_queue = queue.Queue()
def thread_function():
try:
# 線程邏輯
pass
except Exception as e:
# 將異常信息放入隊列
exception_queue.put(e)
# 創建線程
thread = threading.Thread(target=thread_function)
# 啟動線程
thread.start()
# 等待線程結束
thread.join()
# 檢查異常信息
if not exception_queue.empty():
exception = exception_queue.get()
print("Thread exception:", exception)
無論使用哪種方式,都需要在主線程中檢查是否有異常發生,并處理異常信息。
丸趣 TV 網 – 提供最優質的資源集合!
正文完