在python中捕获`threadpoolexecutor`异常,核心做法是调用`future.result()`方法并包裹在`try-except`块中。由于线程池提交的任务默认不抛出异常到主线程,必须通过获取`future`对象的结果来触发异常的重新抛出。如果任务被取消或执行失败,`result()`会分别抛出`cancellederror`或原始的业务/运行时异常,从而允许主程序进行统一处理。

submit返回的Future对象如何关联异常
当使用submit方法提交任务时,它会立即返回一个concurrent.futures.Future实例。这个实例并不直接包含异常,而是作为任务的句柄。只有当你显式调用该实例的result()方法时,如果任务在执行过程中抛出了异常,该异常才会从result()调用处重新抛出。这意味着,如果你只调用submit而不调用result(),异常会被静默吞没,程序不会崩溃,但错误也无法被捕获。因此,建立“提交-获取结果”的闭环是捕获异常的前提。

from concurrent.futures import ThreadPoolExecutor, Future
def task_with_error():
raise ValueError("Task failed intentionally")
with ThreadPoolExecutor(max_workers=1) as executor:
future: Future = executor.submit(task_with_error)
try:
# 这行代码会触发异常的重新抛出
result = future.result()
except ValueError as e:
print(f"Caught exception: {e}")
except Exception as e:
print(f"Caught other exception: {e}")
批量提交时如何逐个捕获不同任务的异常
在批量提交多个任务时,通常使用列表推导式或循环收集所有的Future对象。为了逐个捕获每个任务的异常,需要遍历这些Future对象,并对每一个单独调用result()。如果在遍历过程中某个result()抛出异常,可以使用try-except块隔离单个任务的失败,防止其中断对其他任务结果的获取。这种模式适用于需要知道哪些任务成功、哪些失败的场景,而不是让一个任务的失败导致整个批处理的中断。
Nodriver是Undetected-Chromedriver的官方继承者,提供异步浏览器自动化功能,可直接与Chrome DevTools Protocol通信,无需Selenium或WebDriver依赖。专为规避反机器人系统(包括Cloudflare和Imperva)的隐蔽网络自动化而构建。
立即学习“Python免费学习笔记(深入)”;

from concurrent.futures import ThreadPoolExecutor
def risky_task(n):
if n == 2:
raise RuntimeError(f"Failed on {n}")
return n * 2
with ThreadPoolExecutor(max_workers=3) as executor:
futures = [executor.submit(risky_task, i) for i in range(5)]
for i, future in enumerate(futures):
try:
res = future.result()
print(f"Task {i} result: {res}")
except RuntimeError as e:
print(f"Task {i} error: {e}")
except Exception as e:
print(f"Task {i} unexpected error: {e}")
当任务被取消时result()会抛出什么异常
如果在调用result()之前,通过future.cancel()成功取消了任务,或者任务因超时(在result(timeout=...)中)而终止,result()方法将抛出concurrent.futures.CancelledError。这是一个特定的异常类型,继承自OSError。在捕获异常时,应当将其与普通的业务异常区分开,因为取消操作通常是预期的控制流,而非错误。此外,如果cancel()返回False,说明任务已经开始执行且无法取消,此时调用result()仍会等待任务完成并可能抛出业务异常。
from concurrent.futures import ThreadPoolExecutor, CancelledError
import time
def long_running_task():
time.sleep(10)
return "done"
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(long_running_task)
# 尝试取消任务
cancelled = future.cancel()
if cancelled:
try:
future.result()
except CancelledError:
print("Task was successfully cancelled and CancelledError raised.")
else:
print("Task could not be cancelled, waiting for result...")
try:
future.result()
except Exception as e:
print(f"Task finished with error: {e}")

















