function ErrorCatchDemo
%
% Show how to use try and catch to allow cleanup after
% an error in M-files.
%
% 12/19/03  dhb  Wrote it based on suggestion from Scott French.

% Make sure undefinedvar is an undefined variable, so that referencing
% it causes an error.
clear undefinedvar
lasterr('');

% Enclose all your real code between try and catch.  Here we
% just open the screen and then execute a statement that causes
% an error.
try
	%Screen(0,'OpenWindow',0,[],32);
	error('This is an error');

% If an error occurs, the catch statements executed.  Clear
% mex causes all Psychtoolbox mex files to exit gracefully.
% Then pick up the error with MATLAB function lasterr and
% report it using a call to error().
catch
	%Screen('CloseAll');
end
error(lasterr);
lasterr
