簡體   English   中英

matlab中的條件try catch語句

[英]Conditional try catch statement in matlab

我正在尋找一種優雅的方式來使用條件try catch語句。

我想它看起來像這樣:

tryif loose==1
% Do something, like loading the user preferences
catch %Or catchif?
% Hande it
end

到目前為止,我知道您可以使用try catch塊來運行已編譯的代碼,但dbstop if caught error ,則強制它在dbstop if caught error的調試會話中停止。 現在我基本上尋找相反的事情

通常我希望代碼在發生意外情況時停止(以保證結果的完整性)但是在我調試時有時會對某些事情不那么嚴格。

這個怎么樣:

try
  % Do something, like loading the user preferences
catch exception
  if loose ~= 1
    rethrow(exception)
  end
  % Handle it
end

我不知道優雅;-),但至少它避免了“做某事”的重復。

我知道一種方法,雖然我很難稱之為優雅:

if loose == 1
  try
    % Do something, like loading the user preferences
  catch
    % Hande it
  end
else
  % Do something, like loading the user preferences
end

我能做的最好的事情是:

try
    % Do something, like loading the user preferences
catch me
    errorLogger(me);
    %Handle the error
end

然后

function errorLogger(me)
LOOSE = true;    
%LOOSE could also be a function-defined constant, if you want multiple uses.  
%    (See: http://blogs.mathworks.com/loren/2006/09/13/constants/)

if LOOSE
    %Log the error using a logger tool.  I use java.util.logging classes, 
    %but I think there may be better options available.
else
    rethrow(me);
end

然后,如果需要進行生產型部署,請避免像這樣的常量條件檢查:

function errorLogger(me)
%Error logging disabled for deployment

對於“ tryif ”功能,您可以在try塊的第一行assert

try
    assert(loose==1)
    % Do something
catch err
    if strcmp(err.identifier,'MATLAB:assertion:failed'),
    else
    % Hande error from code following assert
    end
end

請注意,如果loose==1則不會執行"Do something"代碼。

對於“ catchif ”功能,A.Donda在catch塊的第一行檢查loose~=1的方法似乎相當不錯。

暫無
暫無

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

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