MATLAB: How to make a subfunction return to the highest level function in MATLAB 7.6 (R2008a)

MATLAB

I have a function which calls a subfunction which calls another subfunction and so on. I would like one of the lower level subfunctions return to the main function if a certain condition is satisfied.

Best Answer

To make one of lower level subfunctions return to the main function, you can throw a custom MException inside the low level function and put TRY-CATCH block in the main function to catch this exception. For example, see the code below:
% The highest level function
function main
try
foo1
disp('Hello World level0')
catch ME
disp(ME.message)
end
end
% 1st level function
function foo1
foo2;
disp('Hello World level1')
end
% 2nd level function which should return to the main function if a
% condition is satisfied
function foo2
% specify a condition
if 2>0
% create a custom exception
ME = MException('Foo:Bar','Exception is thrown');
throw(ME)
end
disp('Hello World level2')
end