在不崩溃的情况下测试 netcdf 文件是否有效
test if netcdf file is valid without crashing
我正在使用 matlab 中的 ncread
函数读取多个 netcdf 文件。
由于我不知道的原因,某些文件(在下文中由 FILEPATH
描述)未正确读取并且 ncread
崩溃,产生错误消息:
Error using internal.matlab.imagesci.nc/openToRead (line 1259)
Could not open FILEPATH for reading.
Error in internal.matlab.imagesci.nc (line 121) this.openToRead();
Error in ncread (line 53)
ncObj = internal.matlab.imagesci.nc(ncFile);
Error in MY_FUNCTION (line 102)
Lon = nanmean(ncread(FILEPATH,'Lon'));
如果您知道在不崩溃的情况下测试 netcdf 文件的方法,或者如果您了解导致此错误的原因,我们将不胜感激。
标准的做法是将possibly-failing语句包裹在try
/catch
语句中,在中断函数执行前拦截抛出的异常,像这样:
function [out1, out2, ...] = MY_FUNCTION(arg1, arg2, ...)
%//Initial code
try
Lon_data = ncread(FILEPATH,'Lon');
catch ME
warning('MY_FUNCTION:ncread', 'Could not load because <<%s>>',ME.message);
%//Do something to recover from error
%//Return from function if recover not possible
end;
Lon = nanmean(Lon_data);
%//Rest of the code
end
请注意,上面函数签名中的 ...
不是有效的 MATLAB 语法,而是 "here are some inputs and outputs that I don't know how they are declared";请替换为您正确的 in/out 声明。
我正在使用 matlab 中的 ncread
函数读取多个 netcdf 文件。
由于我不知道的原因,某些文件(在下文中由 FILEPATH
描述)未正确读取并且 ncread
崩溃,产生错误消息:
Error using internal.matlab.imagesci.nc/openToRead (line 1259)
Could not open FILEPATH for reading.
Error in internal.matlab.imagesci.nc (line 121) this.openToRead();
Error in ncread (line 53)
ncObj = internal.matlab.imagesci.nc(ncFile);
Error in MY_FUNCTION (line 102)
Lon = nanmean(ncread(FILEPATH,'Lon'));
如果您知道在不崩溃的情况下测试 netcdf 文件的方法,或者如果您了解导致此错误的原因,我们将不胜感激。
标准的做法是将possibly-failing语句包裹在try
/catch
语句中,在中断函数执行前拦截抛出的异常,像这样:
function [out1, out2, ...] = MY_FUNCTION(arg1, arg2, ...)
%//Initial code
try
Lon_data = ncread(FILEPATH,'Lon');
catch ME
warning('MY_FUNCTION:ncread', 'Could not load because <<%s>>',ME.message);
%//Do something to recover from error
%//Return from function if recover not possible
end;
Lon = nanmean(Lon_data);
%//Rest of the code
end
请注意,上面函数签名中的 ...
不是有效的 MATLAB 语法,而是 "here are some inputs and outputs that I don't know how they are declared";请替换为您正确的 in/out 声明。