Is there a way to abort the code inside a function?
17 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Guillaume
on 9 Nov 2014
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 Comments
Guillaume
on 10 Nov 2014
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.
More Answers (1)
See Also
Categories
Find more on Debugging and Analysis in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!