2012-08-24 146 views
3

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

mymatrix = load("input.txt"); 

如果input.txt中中有一些不好的行,倍频程这样的事情barfs:

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块,什么是正确的语法?

我希望能够清楚准确地向用户报告输入文件有问题(丢失,错误配置的列,太多的列,错误的字符等),并恢复。不仅仅是发现神秘的错误并停止。什么是最好的方式来做到这一点?

回答

2

首先,阅读official documentation on Octave try/catch

general exception handling

下面是正确的语法赶在GNU八度异常:

%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 

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

+4

在捕获错误消息后打印错误消息是一种很好的做法。我建议在catch块上使用'printf(“无法加载文件:%s \ n”,lasterr)'。 – carandraug