【问题标题】:In GNU Octave, how to catch an exception在 GNU Octave 中,如何捕获异常
【发布时间】:2012-08-20 08:25:42
【问题描述】:

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

mymatrix = load("input.txt");

如果 input.txt 中有一些不好的行,八度音阶就会出现这种情况:

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

我希望能够干净、准确地向用户报告输入文件有问题(丢失、错误配置的列、太多列、错误字符等)并恢复。不只是吐出神秘的错误并停止。最好的方法是什么?

【问题讨论】:

    标签: exception exception-handling try-catch octave


    【解决方案1】:

    首先,阅读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 没有定义。

    【讨论】:

    • 捕捉到错误信息后打印是个好习惯。我建议在 catch 块上使用printf ("Unable to load file: %s\n", lasterr)
    猜你喜欢
    • 2011-04-03
    • 2021-03-26
    • 2013-09-04
    • 2021-05-23
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-16
    相关资源
    最近更新 更多