throw (MException) - Terminate function and issue exception

Syntax

throw(ME)

Description

throw(ME) terminates the currently running function, issues an exception based on MException object ME, and returns control to the keyboard or to any enclosing catch block. A thrown MException displays a message in the Command Window unless it is caught by try-catch. throw also sets the MException stack field to the location from which the throw method was called.

Examples

Example 1

This example tests the output of M-file evaluate_plots and throws an exception if it is not acceptable:

[minval, maxval] = evaluate_plots(p24, p28, p41);
if minval < lower_bound || maxval > upper_bound
    ME = MException('VerifyOutput:OutOfBounds', ...
       'Results are outside the allowable limits');
    throw(ME);
end

Example 2

This example attempts to open a file in a directory that is not on the MATLAB path. It uses a nested try-catch block to give the user the opportunity to extend the path. If the file still cannot be found, the program issues an exception with the first error appended to the second:

function data = read_it(filename);
try
   fid = fopen(filename, 'r');
   data = fread(fid);
catch eObj1
   if strcmp(eObj1.identifier, 'MATLAB:FileIO:InvalidFid')
      msg = sprintf('\n%s%s%s', 'Cannot open file ', ...
         filename, '. Try another location?  ');
      reply = input(msg, 's')
      if reply(1) == 'y'
          newdir = input('Enter directory name:  ', 's');
      else
          throw(eObj1);
      end
      addpath(newdir);
      try
         fid = fopen(filename, 'r');
         data = fread(fid);
      catch eObj2
         eObj3 = addCause(eObj2, eObj1)
         throw(eObj3);
      end
      rmpath(newdir);
   end
end
fclose(fid);

If you run this function in a try-catch block at the command line, you can look at the MException object by assigning it to a variable (e) with the catch command.

try
   d = read_it('anytextfile.txt');
catch e
end

e
e =
	MException object with properties:

    identifier: 'MATLAB:FileIO:InvalidFid'
       message: 'Invalid file identifier.  Use fopen to 
generate a valid file identifier.'
         stack: [1x1 struct]
         cause: {[1x1 MException]}

  Cannot open file anytextfile.txt. Try another location?y
Enter directory name:  xxxxxxx
Warning: Name is nonexistent or not a directory: xxxxxxx.
> In path at 110
  In addpath at 89

See Also

error, try, catch, assert, MException, rethrow(MException), throwAsCaller(MException), addCause(MException), getReport(MException), disp(MException), isequal(MException), eq(MException), ne(MException), last(MException),

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS