Python 相当于 MATLAB 的 rethrow()
Python equivalent of MATLAB's rethrow()
我正在尝试在 Python 中移植一个工作的 MATLAB 代码。我正在尝试创建大小为 (rows
、cols
) 的 var
数组。如果引发异常,我会捕获它并再次尝试创建大小为 (rows
、cols
-1) 的 var
数组。如果 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
的文档指出:
Instead of creating the stack from where MATLAB executes the method, rethrow
preserves the original exception information and enables you to retrace the source of the original error.
我的问题是:我应该在 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)
对应的语法就是raise
: raise e
(注意:它不是一个函数)为它自己添加一个stacktrace条目。 (在 Python 2 中,它 替换了 以前的堆栈跟踪,就像 MATLAB 的普通 throw
,但 Python 3 扩展了它。)
我正在尝试在 Python 中移植一个工作的 MATLAB 代码。我正在尝试创建大小为 (rows
、cols
) 的 var
数组。如果引发异常,我会捕获它并再次尝试创建大小为 (rows
、cols
-1) 的 var
数组。如果 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
的文档指出:
Instead of creating the stack from where MATLAB executes the method,
rethrow
preserves the original exception information and enables you to retrace the source of the original error.
我的问题是:我应该在 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)
对应的语法就是raise
: raise e
(注意:它不是一个函数)为它自己添加一个stacktrace条目。 (在 Python 2 中,它 替换了 以前的堆栈跟踪,就像 MATLAB 的普通 throw
,但 Python 3 扩展了它。)