简体   繁体   中英

Conditional try catch statement in matlab

I am looking for an elegant way to use a conditional try catch statement.

I suppose it could look something like this:

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

So far I know that you can use try catch blocks to let your compiled code run, but force it to stop in a debug session with dbstop if caught error . Now I am basically looking for the opposite :

Normally I want the code to stop if unexpected situations occur (to guarantee the integrity of results) but want to be less strict about certain things sometimes when I am debugging.

How about this:

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

I don't know about elegant ;-), but at least it avoids the duplication of "do something".

I know one way to do it, though I would hardly call this elegant:

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

The best I've been able to do is:

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

And then

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

Then, if desired for production-style deployments, avoid the constant condition checking like this:

function errorLogger(me)
%Error logging disabled for deployment

For the " tryif " functionality, you could assert on the first line of the try block:

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

Note that the "Do something" code will not be executed if loose==1 .

For the " catchif " functionality, A.Donda's approach of checking loose~=1 on the first line of the catch block seems quite good.

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