MATLAB: Catching Error in Subfunction with Global try/catch

guitry/catch

Hi, I have GUI that runs from CSTMainWindow.m. From there a GUI displays which can lead to other GUIs, coded in different files.
I want it to have a bug reporting system. Normally CSTMainWindow is the function run to starting everything, but I changed it so that the function run is CeleST, defined below:
function CeleST
try
% Global try-catch on CeleST
CSTMainWindow()
catch exception
generateReport(exception)
end
generateReport is the bugReporter, just sends an e-mail to me with error stack and a message from the user.
QUESTION: The CSTMainWindow GUI has pushButtons that call other GUI files. However when an error occurs there, it is not caught by the try/catch block. Is this because they are subfunctions, or could it be something I'm not aware of in how the try/catch system works?
Below is an example of one pushButton defintion in CSTMainWindow as well as the subfunction it calls:
uicontrol('parent',mainPanel,'style','pushbutton','string','2. Compute measures...','position',[700 yFilters+hFilters+10 170 60],'callback',@checkResults);
;
function checkResults(hObject,eventdata) %#ok<INUSD>
set(mainFigure,'Visible','off');
CSTCheckResults
set(mainFigure,'Visible','on');
flagConsistentButton = false;
checkSequences
populateFilters
end
And the error that is not caught (q is an undefined fake variable to purposely cause an error):
Undefined function or variable 'q'.
Error in CSTCheckResults (line 109)
filterH = q;
Error in CSTMainWindow/checkResults (line 234)
CSTCheckResults
Error using waitfor
Error while evaluating UIControl Callback
As said earlier, CSTCheckResults is a programmatic GUI file

Best Answer

GUI's return to the calling routine when all of the code in their function has been executed. If the code sets up graphics elements (figures, controls, and so on), then executing that setup is all that is done and the routine returns after that.
The exception to this is if the routine uses uiwait() or waitfor(), in which case the routine does not continue on to the next statement until the requested event has occurred.
However, Callbacks of all kinds are executed in the context of the base workspace, not in the context of the routine that set the Callback function. You can only "catch" the exceptions of statements you call directly, not of functions automatically executed on your behalf through a callback.
Work around: everywhere you have a Callback set, instead of giving the name of the routine directly, give the name of an error-trap routine with a parameter of the routine that does the actual work:
... 'Callback', @frobnoz_button1_Callback, ...
becoming
... 'Callback', {@traperrors, @frobnoz_button1_Callback)
function traperrors(src,event,real_routine,varargin)
try
real_routine(src, event, varargin{:});
catch exception
report_error(exception);
end