Javatpoint Logo
Javatpoint Logo

MATLAB Error Control Statement-try, catch

MATLAB define some functions that are used to control error. The try-catch statement is an error control function, which is explained below.

Try - catch statement

Try-catch statement provides error handling control. General form of the try-catch statement is

Syntax:

Statements between try and catch execute first. If no error appears in executing statements between try and catch, MATLAB further executes the statements/code after the end keyword. If an error occurs during the execution of statements between try and catch, MATLAB executes statements between catch and end. Try-catch statement can be explained with the help of the following example.

Example:

Output:

 
 MException with properties:

    identifier: 'MATLAB:catenate:dimensionMismatch'
       message: 'Dimensions of arrays being concatenated are not consistent.'
         cause: {01 cell}
         stack: [31 struct]
    Correction: []

MATLAB Error Control Statement-try, catch

Following are the points while using a try/catch statement in MATLAB:

  • The control of the program execution first enters the try block and executes each statement.
  • If any error occurs during the execution, then the control immediately passes to the catch block, leaving any other statements of the try block unexecuted.
  • If there is no error occurs inside try block, then the control doesn't enter the catch block. The control then reaches to the statements after the end keyword of try/ catch block.
  • Whenever any error or exception occurs in the try block, the MATLAB constructs an instance of the MException class and returns the object in the catch statement.
  • The MException class object can be accessed with the variable ME.
  • The MException class object has five properties-identifier, message, stack, cause, and Correction. These properties describe details about the occurred exception.
  • We can't use multiple catch block, only one catch block within a try block is allowed.
  • We can use nested try/catch blocks if required.

Example showing MException class object properties:

Output:

causeException = 
  MException with properties:

    identifier: 'MATLAB:mycode:dimensions'
       message: 'dimension mismatch occured: First argument has 4 columns, while second argument has 3 columns.'
         cause: {}
         stack: [01 struct]
    Correction: []

Program Termination

Program termination control allows to exit from our program at some point before its normal termination point.


Next TopicMATLAB return




Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA