rethrow (MException) - Reissue existing exception

Syntax

rethrow(ME)

Description

rethrow(ME) terminates the currently running function, reissues an exception that is based on MException object ME that has been caught within a try-catch block, and returns control to the keyboard or to any enclosing catch block.

rethrow differs from the throw and throwAsCaller methods in that it does not modify the stack field. Call stack information in the ME object is kept as it was when the exception was first thrown.

rethrow can only issue a previously caught exception. If an exception that was not previously thrown is passed to the rethrow method, the MATLAB®software generates a new exception.

You might use rethrow from the catch part of a try-catch block, for example, after performing some required cleanup tasks following an error.

Examples

This variation of the MATLAB surf function catches an error in the input arguments, gives the user the opportunity to correct the error, and rethrows the error if the user does not use that opportunity:

function surf2(varargin)
try
   surf(varargin{:})
catch ME
   ME.message      % Display the error.
   % Give user another try to enter input arguments.
   newargs = input('\nEnter argument list: ','s');
   if ~isempty(newargs)
      surf(eval(newargs));
   else
   % If no response from user, rethrow the error.
      rethrow(ME);
   end
end

When asked to correct the error, the user presses Enter. MATLAB rethrows the original error:

surf2
ans =
Not enough input arguments.

Enter argument list: 
??? Error using ==> surf at 54
Not enough input arguments.

Error in ==> surf2 at 3
   surf(varargin{:});

This time, the user enters valid input and MATLAB successfully displays the output plot:

surf2
ans =
Not enough input arguments.

Enter argument list: peaks(30)

See Also

try, catch, error, assert, MException, throw(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