簡體   English   中英

在GNU Octave中,如何捕獲異常

[英]In GNU Octave, how to catch an exception

在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塊,正確的語法是什么?

我希望能夠干凈利落地向用戶報告輸入文件有問題(丟失,配置不正確的列,太多列,不良字符等),然后恢復。 不僅會產生隱秘的錯誤並停止運行。 最好的方法是什么?

首先,請閱讀有關Octave try / catch官方文檔

一般異常處理

這是在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而暫停程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM