MATLAB: Error “Invalid or deleted object.” when close a GUI in App Designer

app designer

Hi, I tried to create an app simply to display capture from a webcam. The main functions are like below.
properties (Access = private)
KeepRunning = 1;
cam = webcam('USB Video Device');
end
methods (Access = private)
% Code that executes after component creation
function startupFcn(app)
app.cam.Resolution = '640x480';
while 1
rgbImage = snapshot(app.cam);
imshow(rgbImage,'Parent',app.UIAxes);
drawnow;
end
end
% Close request function: UIFigure
function UIFigureCloseRequest(app, event)
delete(app.cam)
delete(app)
end
end
Everything works fine; however, as I close the GUI (using X button), this error popped up. Any ideas?
Invalid or deleted object.
Error in app_test/startupFcn (line 23)
rgbImage = snapshot(app.cam);
Error in app_test (line 84)
runStartupFcn(app, @startupFcn)

Best Answer

I'm not convinced of the wisdom of having a never ending loop in your startupFcn.
Anyway, the problem is simple when you close the app, your close request callback deletes app.cam making it an invalid handle. Your infinite loop in startupFcn is still running and tries to access the now deleted app.cam, hence the error.
The naive fix would be to change the
while 1
to
while isvalid(app.cam)
99% of the time, it'll fix the error. However, were the user to close the app just after the while has executed but before the snapshot line has executed, you'll still get the error. A foolproof way would be:
while true
try
rgbImage = snapshot(app.cam);
catch
%error occured, probably app.cam was deleted. Quit loop
break;
end
imshow(rgbImage,'Parent',app.UIAxes);
drawnow;
end