我正在嘗試在 Python 中移植一個有效的 MATLAB 代碼。我正在嘗試創建var大小為 ( rows, cols)的陣列。如果引發例外,我會捕獲它并再次嘗試創建var大小為 ( rows, cols-1)的陣列。如果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)
uj5u.com熱心網友回復:
相應的語法只是raise:(raise e注意:它不是函式)為自己添加一個堆疊跟蹤條目。(在 Python 2 中,它像 MATLAB 的普通 一樣替換了之前的堆疊跟蹤throw,但 Python 3 擴展了它。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/350374.html
