[英]Conditional try catch statement in matlab
I am looking for an elegant way to use a conditional try catch
statement. 我正在寻找一种优雅的方式来使用条件try catch
语句。
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
. 到目前为止,我知道您可以使用try catch
块来运行已编译的代码,但dbstop if caught error
,则强制它在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: 对于“ 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
Note that the "Do something"
code will not be executed if loose==1
. 请注意,如果loose==1
则不会执行"Do something"
代码。
For the " catchif
" functionality, A.Donda's approach of checking loose~=1
on the first line of the catch
block seems quite good. 对于“ catchif
”功能,A.Donda在catch
块的第一行检查loose~=1
的方法似乎相当不错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.