我正在尝试在 Python 中移植一个工作的 MATLAB 代码。我正在尝试创建大小为 ( , )的var
数组。如果引发异常,我会捕获它并再次尝试创建大小为 ( , -1) 的数组。如果变为零,那么我不能做任何其他事情,所以我之前捕获的异常。rows
cols
var
rows
cols
cols
rethrow
代码片段如下:
% rows, cols init
success = false;
while(~success)
try
var = zeros(rows, cols);
success = True;
catch ME
warning('process memory','Decreasing cols value because out of memory');
success = false;
var = [];
cols = cols - 1;
if (cols < 1)
rethrow(ME);
end
end
end
国家文件rethrow
:
无需从 MATLAB 执行方法的位置创建堆栈,而是
rethrow
保留原始异常信息并使您能够追溯原始错误的来源。
我的问题是:我应该在 Python 中编写什么才能获得与 MATLAB 相同的结果rethrow
?
在 Python 中,我编写了以下内容。这足够了吗?
# rows, cols init
success = False
while not success:
try:
var = np.zeros([rows, cols])
success = True
except MemoryError as e:
print('Process memory: Decreasing cols value because out of memory')
success = False
var = []
cols -= 1
if cols < 1:
raise(e)