Error Handling in Simulink Using MSLException
Error Reporting in a Simulink Application
Simulink® allows you to report an error by throwing an exception using the
MSLException
object, which is a subclass of the MATLAB®
MException
class. As with the MATLAB
MException
object, you can use a try-catch
block with a
MSLException
object construct 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.
The MSLException Class
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.
Methods of the MSLException Class
The methods for the MSLException
class are identical to those of the
MException
class. For details of these methods, see MException
.
Capturing Information About the Error
The structure of the Simulink
try-catch
block for capturing an exception is:
try Perform one or more operations catch E if isa(E, 'MSLException') ... end
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
Simulink specific, i.e., an MSLException
. In other words, an
MSLException
is a type of MException
.
The following code example shows how to get the handles associated with an error.
errHndls = []; try sim('ModelName', ParamStruct); catch e if isa(e,'MSLException') errHndls = e.handles{1} end end
You can see the results by examining e. They will be similar to the following output:
e = MSLException Properties: handles: {[7.0010]} identifier: 'Simulink:Parameters:BlkParamUndefined' message: [1x87 char] cause: {0x1 cell} stack: [0x1 struct] Methods, Superclasses
To identify the name of the block that threw the error, use the
getfullname
command. For the present example, enter the following
command at the MATLAB command line:
getfullname(errHndls)
If a block named Mu threw an error from a model named vdp,
MATLAB would respond to the getfullname
command with:
ans = vdp/Mu