function testerror(fn, id, msg) %TESTERROR check that a function throws an expected error % % testerror(fn[, id[, msg]]) % testerror(@() statement[, id[, msg]]) % % Test that a function, possibly created on the fly for a bad statement, throws % an error. Optionally check that the error string is the one expected. % % OK or FAILURE is verbosely reported. This is for use in test cases. % % Inputs: % fn @fn handle to test function (should take no arguments) % id str OPTIONAL: expected error id string (empty or missing to bypass check) % msg str OPTIONAL: expected error message string % Iain Murray, September 2010 try fn(); %catch me catch % Instead of the 'catch me' line, do a plain catch with the (deprecated) % following line for compatability with older Matlab/Octave [me.message, me.identifier] = lasterr; if (nargin > 1) && ~isempty(id) if ~isequal(me.identifier, id) fprintf('FAILURE: unexpected error identifier: %s\n', me.identifier); return; end end if (nargin > 2) && ~isempty(msg) if ~isequal(me.message, msg) fprintf('FAILURE: unexpected error message: %s\n', me.message); return; end end fprintf('OK (error was thrown as expected)\n'); return; end fprintf('FAILURE: no error thrown when one was expected\n');