我在Python中重复一系列实验(随机初始化):
num_rounds = 1e3
result_list = []
for i in range(num_rounds):
result = run_experiment() # with random initialization inside the call of `run_experiment`
result_list.append(result)
但是,我的代码可能有问题,可能会中途抛出异常,然后会中断整个循环。
我想知道是否有办法:
或者是否已有工具可以做到这一点?
答案 0 :(得分:1)
1)放开异常并继续循环:
try:
<whatever code can cause exception>
except <Exceptions you want to catch>:
pass
将抓住异常并让它滑倒。或者,您可以在except块中输入continue:
try:
<whatever code can cause exception>
except <Exceptions you want to catch>:
pass
2)和3)使用1中的代码,您可以在except块中收集所需的任何数据,然后继续:
statistics_list = []
for <something>:
try:
<whatever code can cause exception>
except <Exceptions you want to catch>:
statistics_list.append((exception_type, input params....))
continue
循环后,您可以根据自己的喜好处理统计信息列表中的数据
答案 1 :(得分:0)
有try..except..else
:
num_rounds = 1e3
result_list = []
exceptions = {}
for i in range(num_rounds):
values = 1,2,3, ... # with random initialization outside the call of `run_experiment`
try:
result = run_experiment(*values)
except Exception as e:
exceptions[values] = e
else:
result_list.append(result)
答案 2 :(得分:0)
我认为如果像这样修改你的代码,你就可以进行统计。
num_rounds = 1e3
result_list = []
for i in range(num_rounds):
try:
result = run_experiment()
result_list.append(result)
except Exception as ex:
# do statistics
这样您就可以将ex
作为例外,您可以检查并存储该类型。
如果您还想存储随机输入参数,则应在try-except
函数中放置相同的run_experiment