1

我正在尝试在 Python 中移植一个工作的 MATLAB 代码。我正在尝试创建大小为 ( , )的var数组。如果引发异常,我会捕获它并再次尝试创建大小为 ( , -1) 的数组。如果变为零,那么我不能做任何其他事情,所以我之前捕获的异常。rowscolsvarrowscolscolsrethrow

代码片段如下:

% 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)
4

1 回答 1

2

相应的语法只是raise:(raise e注意:它不是一个函数)为自己添加一个堆栈跟踪条目。(在 Python 2 中,它像 MATLAB 的普通 一样替换throw了以前的堆栈跟踪,但 Python 3 扩展了它。)

于 2021-11-04T16:20:33.160 回答