Error Handling in Simulink Using MSLException Objects
Error Reporting in Simulink Applications
Simulink® allows you to report an error by throwing an exception using the
MSLException object, which is based on the MATLAB®
MException object. As with the MATLAB
MException object, you can use a try-catch block with a
MSLException object to capture information about the error. The primary
distinction between the MSLException and the MException
objects is that the MSLException object has the additional property of
handles. These handles allow you to identify the object associated with the error.
MSLException Objects
The MSLException class has five properties:
identifier, message, stack,
cause, and handles. The first four of these
properties are identical to those of MException. For detailed information
about them, see MException. The fifth property,
handles, is a cell array with elements that are double array. These
elements contain the handles to the Simulink objects (blocks or block diagrams) associated with the error.
MSLException Object Functions
The functions for the MSLException object are identical to those of the
MSLException object. For details of these functions, see MException.
Capturing Information About the Error
This code shows the structure of the try-catch block for capturing an
MSLException. If an operation within the try
statement causes an error, the catch statement catches the exception
E. Next, an if isa conditional statement tests to
determine if the exception is an MSLException object, which indicates that
the exception came from Simulink specific. In other words, an MSLException is a type of
MException.
try Perform one or more operations catch E if isa(E, 'MSLException') ... end
This code example shows how to get the handles associated with an error.
errHndls = [];
try
sim('ModelName');
catch e
if isa(e,'MSLException')
errHndls = e.handles{1}
end
end
You can see the results by examining the variable e. The results look
similar to this output.
e =
MSLException
Properties:
handles: {[7.0010]}
identifier: 'Simulink:Parameters:BlkParamUndefined'
message: [1x87 char]
cause: {0x1 cell}
stack: [0x1 struct]
Methods, SuperclassesTo identify the name of the block that threw the error, use the
getfullname function. For the present example, enter this command in
the MATLAB Command Window.
getfullname(errHndls)
If a block named Mu threw an error from a model named
vdp, the getfullname function returns the path to
the block named Mu.
ans = vdp/Mu