throwAsCaller (MException) - Throw exception, as if from calling function

Syntax

throwAsCaller(ME)

Description

throwAsCaller(ME) throws an exception from the currently running M-file based on MException object ME. The MATLAB software exits the currently running function and returns control to either the keyboard or an enclosing catch block in a calling function. Unlike the throw function, MATLAB omits the current stack frame from the stack field of the MException, thus making the exception look as if it is being thrown by the caller of the function.

In some cases, it is not relevant to show the person running your program the true location that generated an exception, but is better to point to the calling function where the problem really lies. You might also find throwAsCaller useful when you want to simplify the error display, or when you have code that you do not want made public.

Examples

The function klein_bottle, in this example, generates a Klein Bottle figure by revolving the figure-eight curve defined by XYKLEIN. It defines a few variables and calls the function draw_klein, which executes three functions in a try-catch block. If there is an error, the catch block issues an exception using either throw or throwAsCaller:

function klein_bottle(ab, pq)
rtr = [2 0.5 1];
box = [-3 3 -3 3 -2 2];
vue = [55 60];
draw_klein(ab, rtr, pq, box, vue)


function draw_klein(ab, rtr, pq, box, vue)
clf
try
   tube('xyklein',ab, rtr, pq, box, vue);
   shading interp
   colormap(pink);
catch ME
   throw(ME)
%   throwAsCaller(ME)
end

Call the klein_bottle function, passing an incorrect value for the second argument. (The correct value would be a vector, such as [40 40].) Because the catch block issues the exception using throw, MATLAB displays error messages for line 15 of function draw_klein, and for line 5 of function klein_bottle:

klein_bottle(ab, pi)
??? Attempted to access pq(2); index out of bounds because 
   numel(pq)=1.

Error in ==> klein_bottle>draw_klein at 15
   throw(ME);

Error in ==> klein_bottle at 5
draw_figure(ab, rtr, pq, box, vue)

Run the function again, this time changing the klein_bottle.m file so that the catch block uses throwAsCaller instead of throw. This time, MATLAB only displays the error at line 5 of the main program:

klein_bottle(ab, pi)
??? Attempted to access pq(2); index out of bounds because 
   numel(pq)=1.

Error in ==> klein_bottle at 5
draw_figure(ab, rtr, pq, box, vue)

See Also

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