When an error occurs in a try
block, MATLAB transfers control to the
catch
block. If the catch
block has
an identifier, MATLAB enters the catch
block with the
identifier set to an MException
object that contains the
error message, the message ID, and the stack trace. You can use this object with
functions such as rethrow
to pass the error to the code
that called it. Not only does the object always contain information about the
correct error, there is no longer any need to save the
lasterr
around the try/catch
block
to avoid breaking old code. For more information, see “Capturing Information About the Error”.
Use an identifier on the catch
block. If the
catch
block has an identifier, the state of
lasterr
and lasterror
are
unchanged. Typically, you can replace a call to lasterror
with the
catch
block identifier, and you can replace a call to lasterr
by referencing
the message field of this identifier. You can probably remove any code that
saves the previous state of lasterr
and
lasterror
. The resulting code is typically smaller,
clearer, and faster than the older code.