I'm trying to port a working MATLAB code in Python. I am trying to create the var
array with size (rows
, cols
). If an exception is raised, I catch it and try again to create the var
array with size (rows
, cols
-1). If cols
gets to zero, then I cannot do anything else, so I rethrow
the previously caught exception.
The code snippet is as follows:
% 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
The doc of rethrow
states:
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.
My question is: What should I write in Python to have the same results with MATLAB's rethrow
?
In Python, I wrote the following. Is that sufficient?
# 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)
CodePudding user response:
The corresponding syntax is just raise
: raise e
(note: it’s not a function) adds a stacktrace entry for itself. (In Python 2, it replaced the previous stacktrace like MATLAB’s ordinary throw
, but Python 3 extends it.)