[英]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.