在GNU Octave中,如何捕获异常

在GNU Octave中捕获异常的正确语法是什么?如果没有文件,我有一行失败:

mymatrix = load("input.txt");

如果input.txt中有一些不好的行,则使用以下类似的八度barf:

error: load: unable to extract matrix size from file `input.txt'
error: called from:
error: /home/el/loadData.m at line 93, column 20
error: main at line 37, column 86
error: /home/el/main.m at line 132, column 5

我想在Octave中使用try / catch块,正确的语法是什么?

我希望能够干净准确地向用户报告输入文件出现问题(丢失,列数不正确,列数太多,字符不正确等),然后恢复.不只是吐出神秘的错误而且停止了.最好的方法是什么?

最佳答案 首先,阅读
official documentation on Octave try/catch

general exception handling

以下是在GNU Octave中捕获异常的正确语法:

%make sure foobar.txt does not exist.
%Put this code in mytest.m.

try
  mymatrix = load("foobar.txt");   %this line throws an exception because 
                                   %foobar does not exist.
catch
  printf ("Unable to load file: %s\n", lasterr)
end


disp(mymatrix)  %The program will reach this line when the load command
%fails due to missing input file.  The octave catch block eats the 
%exception and ignores it.

当您运行上面的代码时,这将打印:

Unable to load file: load: unable to find file foobar.txt

然后忽略从加载文件抛出的异常,因为未在try块中定义disp(mymatrix),因为没有定义mymatrix,所以另外的异常会暂停程序.

点赞