简体   繁体   中英

In GNU Octave, how to catch an exception

What is the correct syntax for catching an exception in GNU Octave? I have a line that fails if there is no file present:

mymatrix = load("input.txt");

If input.txt has some bad rows in it, octave barfs with this sort of thing:

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

I'd like to use a try/catch block in Octave, what is the proper syntax?

I want to be able to report cleanly and accurately to the user that something is wrong with the input file (missing, incorrectly configured columns, too many columns, bad characters, etc), and recover. Not just spew cryptic errors and halt. what is the best way to do that?

First, read the official documentation on Octave try/catch

and general exception handling

Here is the correct syntax to catch an exception in 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.

When you run the above code, this prints:

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

Then the exception thrown from the load file is ignored, since disp(mymatrix) was not defined in the try block, an additional exception halts the program because mymatrix is not defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM