Loren on the Art of MATLAB

Turn ideas into MATLAB

Exceptional Behavior 18

Posted by Loren Shure,

One of the new features of MATLAB in R2007b is a more robust way to manage and reporting errors. We have found that using an MException object, instead of relying on lasterror, has reduced one sort of coding error. The reason why the new way is better is because lasterror is a global state and can be easily corrupted. This can happen in a try/catch where you don't want to throw an error but do something else instead. However, landing in the catch updates lasterror so unless you save its state and later restore it, you may cause some unexpected behavior. In addition, MException objects allow us to readily augment the information conveyed in an error message. Let's see a little bit about how MException objects work.

Contents

try and catch E

You can generate an MException using new syntax for try/catch. As you can see in the following code, you can generate an MException object now. In the catch segment of code, you see I choose to simply display the message here.

a = [3 , 2]
b = [1 ; 7]
try
    c = a + b;
catch myEx
    disp(myEx.message)
end
a =
     3     2
b =
     1
     7
Matrix dimensions must agree.

Here's the full display of this MException.

myEx
myEx =

	MException object with properties:

    identifier: 'MATLAB:dimagree'
       message: 'Matrix dimensions must agree.'
         stack: [4x1 struct]
         cause: {}

In addition to the message, it has a message identifier, information about the calling stack, and a cause (another, often underlying MException). Get the full details on these properties here.

Adding cause

To explain more about what's happened, you can add a cause which is another MException, to the original MException. Here's another way to generate an MException.

newME = MException('Loren:Blog:MExcepExampleAddCause',...
    'Vector orientations don''t match.');
myEx = addCause(myEx,newME)
myEx =

	MException object with properties:

    identifier: 'MATLAB:dimagree'
       message: 'Matrix dimensions must agree.'
         stack: [4x1 struct]
         cause: {[1x1 MException]}

And to see the added cause, extract it.

myEx.cause{1}
ans =

	MException object with properties:

    identifier: 'Loren:Blog:MExcepExampleAddCause'
       message: 'Vector orientations don't match.'
         stack: [0x1 struct]
         cause: {}

What about error?

There is no difference currently between calling error and throwing an exception directly, since error already throws an exception internally. error is essentially implemented as:

  throw(MException(id,msg))

The reason to throw an exception directly now is to add causes.

Can You Use This Feature?

Do you see yourself using this feature in some of your applications? Post here to let me know.


Get the MATLAB code

Published with MATLAB® 7.5

9 views (last 30 days)  | |

Comments

To leave a comment, please click here to sign in to your MathWorks Account or create a new one.