function []=testTryCatchErrors()
%   prototype: []=testTryCatchErrors()
%   Created on: 07/25/2011
%   Primary Author: Ed May
%   Last Author:
%   Last edited on: July 25 2011
%   Version: 1.0
%
%   Detailed explanation:
%   A demonstration code or example of how the Try Catch syntax works
%   to detect errors and provide error handling code rather than trap
%   the Octave top level.



% demo/example of try catch syntax
% see http://www.gnu.org/software/octave/doc/interpreter/Catching-Errors.html#Catching-Errors

fprintf(1,'Clearing all variables!\n');
% [status,output]=system (STRING, RETURN_OUTPUT, TYPE);
[status,output]=system('touch file1 file2 file4','sync'); % sync requires octave to wait on completion
if ( status ~= 0 ) 
	fprintf(1,'Non zero status returned by system(touch command: status=%d\n',status);
endif
clear all;
number_of_errors = 0;
number_of_successes = 0;
filePrefix='file';
c=[];
c(1)=1.0;
% prepare a loop which contains both successes and errors.
fprintf(1,"----------------------------------------------\n");
for n = 1:5
       try
	 fprintf(1,"----------------------------------------------\n");
	 fprintf(1,'Beginning of try block with loop n=%d\n',n);
	 filename= [filePrefix num2str(n)];
         fprintf(1,'Will open file filename=%s ',filename);
         fid=fopen(filename,'r');
         fprintf(1,' using fid=%d\n',fid);
         a=mod(n,10);
	 fprintf(fid,'a=%d\n',a);	% attempt to write to file at fid
	 b=1.001*n;
	 if n==2; b=aa/'a'; endif;	% generate a catchable error in loop n=2
	 if n==5; b=c(4); endif;
	 b_value=b
         number_of_successes++;
	 fclose(fid);
	 fprintf('Reached end of try block for loop n=%d\n',n);
       catch
         fprintf('\t===============Caught an error in loop n=%d===============\n',n);
	 msg = error_text;
	 fprintf(1,'\tError Description: %s\n',msg);
         fprintf('\tat n=%d\n',n);
	 lasterr;
         %lasterr.message %causes a trap
         %msg=lasterr.message;  %also causes a trap
         if ( strfind (msg, "undefined") )
		fprintf(1,'\t\tFound matching error.. undefined\n');
         	number_of_errors++;
	 elseif ( strfind(msg, "fprintf") )
		fprintf(1, '\t\tFound matching error.. fprintf error\n');
         	number_of_errors++;
	 else
		% will trap to Octave top level
		rethrow(lasterror);
	 endif
	 fprintf(1,'\t================Reached end of catch block, return to program.\n');
	 b_value=0.0 %assign a default
       end_try_catch
       fprintf('Reached beyond end of end_try_catch block in loop=%d\n',n);
       b_value
endfor
fprintf(1,'Completed n=%d loops.\n',n);
fprintf(1,'n=%d successes=%d errors=%d\n', n, number_of_successes,number_of_errors)

%b=1.0/0;
%fid=fopen('file3','r');
[status,output]=system('/bin/rm file1 file2 file4','sync'); % sync requires octave to wait on completion
if ( status ~= 0 ) 
	fprintf(1,'Non zero status returned by system(remove command: status=%d\n',status);
endif

