Is there a way to abort the code inside a function?
17 次查看(过去 30 天)
显示 更早的评论
Hey there,
Happy to know people are there when there is a challenge. I see that return function is used to abort the code when it appears in the root level of an m-code. But when used in a function, it returns the program flow back to the invoking function.
Having this in mind, I wanna terminate the whole program when a sign of accomplishment is met inside a function. One way seems to be using return for several times to reach the root level. but what's so frustrating here is that this method implies checking the condition in each return again and again till getting into the root.
I know that error function would resolve the issue, but it's not sensible to produce an error when the code is successfully accomplished.
Please advise as necessary.
0 个评论
采纳的回答
Guillaume
2014-11-9
The proper way to do this is indeed to use return and propagate the return value back to the main function.
You can, however, abuse error to do what you want. Throw an error with your own id and catch it in your main:
function out = main(a, b, c)
try
%...
%code that will end up in subfunction
catch exception
if strcmp(exception.msgID, 'poyua:completed')
return;
else
rethrow(exception);
end
end
end
function out = subfunction(d, e)
while true
%...
if completed
error('pouya:completed', '');
end
end
end
2 个评论
Guillaume
2014-11-10
Using error as a control flow structure makes it harder to follow the flow of your program. It's the same reason, the dreaded goto has disappeared from most languages. It violates the layering of your program.
It also restrict the reuseability of your function. Any caller has to expect it may never see the function return. So, if a function opens a file, it needs to make sure that the file is closed before calling any function that could call your terminating subfunction. Otherwise, the file will stay open when the error is raised. You can work around that by implementing an oncleanup in each function that may possibly interrupted, but at that point you may as well implement a proper return.
If your program is fairly small with a fairly simple flow, then using error as flow control may be fine. As the program grows and become more complex, it will probably be a source of bugs.
更多回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Debugging and Analysis 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!