The following article explains how to use the try-catch statement in MATLAB®. The try-catch instruction is one of the most widely used programming languages globally, and its execution mode is the same for all of them. This article includes practical examples and images to help the reader understand how to use this statement to handle errors in real-time execution.

MATLAB try catch Syntax

try

statements

catch exception

statements

end

MATLAB try catch descriptions and examples

A try-catch statement is a tool that gives the program stability and robustness against exceptions or errors in real execution time. These exceptions or errors can be caught so that when one of these events occurs, they can be handled in a predictable and orderly manner and do not affect system performance.

The try-catch statement consists of two blocks: try is the block that encloses the part of the code that can generate an exception or error, and the catch is the block that handles these exceptions to be safely processed. When a try catches an exception, it passes control to catch for processing. Below, we will look at some practical examples using the try-catch statement to understand better how it works.

How to detect and process an exception or error with the try-catch statement in MATLAB

This example shows how to use the try-catch statement against a common error when calculating square roots with the realsqrt() function. This is one of the three basic functions MATLAB has for this type of mathematical operation, and it only accepts real numbers with a positive sign as input arguments. If this rule is not satisfied, an error is generated.

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-133.jpeg" data-lazy- height="755" src="data:image/svg xml,” width=”1440″>

Next, let us look at detecting and handling this error by creating a console application that calculates square roots using the realsqrt() function. This operation is performed in the try block. When an error occurs, control is passed to catch to resolve the calculation using the sqrt() function, which accepts negative or complex numbers.

Create a script, paste this code, and click Run. To close the application, press Ctrl c

while 1

prompt = ‘Enter a value to get its square root.’;

a=input(prompt);

try

x =realsqrt(a);

catch

disp ‘Try found an error and passed the control to catch’

x=sqrt(a);

end

disp([‘The square root is: ‘, num2str(x)])

end

Once the app is up and running, we enter the values we need to calculate the square root.

If negative or complex values are entered, instead of raising an error in the realsqrt() function, it will pass control to catch, and the operation is resolved with the sqrt() function. When this happens, the following message is displayed in the command console:

“Try to find an error and passed the control to catch”

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-134.jpeg" data-lazy- height="757" src="data:image/svg xml,” width=”1440″>

How to identify errors with “MException” and manage them with try catch in MATLAB

Although identifying exceptions with “MException” deserves its own article, we will briefly explain how to use this resource, which helps us identify errors and is an effective complement when using the try-catch statement. MATLAB constructs a “MException” object with information about the error when an error is generated. This information is very useful as we can use it to classify and handle various specific errors. Below you can see the contents of “MException” with information about an error generated by the unique() function.

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-135.jpeg" data-lazy- height="881" src="data:image/svg xml,” width=”1280″>

In the following example, we will see how to retrieve this information to process the errors correctly. To do this, we will create a console application in which we will use the unique() function to generate the errors that we will handle in the catch block and the prompt() function to input the data that will be the input arguments of unique().

When a try catches one of these errors, it stores its information in the “MException”, which we will create with the name “inf_err”, as shown below.

In the catch block, we send a message to the user informing them of detecting an error with the following message “Try has found an error and passed control to catch”.

Then we take the error identifier from the previously created object “err_inf.identifier”. This identifier has the form of a string and gives us information about:

The function that generated it MATLAB:UNIQUE

And the specific error UnknownInput

‘MATLAB:UNIQUE:UnknownInput’

This string will be the argument that the switch conditional will compare with each of the predefined errors in each case.

switch inf_err.identifier

case ‘MATLAB:UNIQUE:UnknownInput’

……

case ‘MATLAB:UNIQUE:UnknownFlag’

……

end

A possible solution to the error or a message to the user will be given in each case.

Create a script, paste this code and run the script. To close the application, press Ctrl C.

ns= [1, 2, 3; 4, 5, 6];

while 1

prompt = ‘Enter a value to get unique.’;

a=input(prompt);

try

x=unique(ns, a);

catch inf_err

disp ‘Try found an error and passed the control to catch’;

disp ([ ‘Error identifier :’ ,inf_err.identifier]);

switch inf_err.identifier

case ‘MATLAB:UNIQUE:UnknownInput’

disp ‘The specified entry could not be found. Please try again.’;

case ‘MATLAB:UNIQUE:UnknownFlag’

disp ‘The unique() function does not recognize the flag:’;

disp(a);

disp ‘Valid flags are ‘rows’, ‘first’, ‘last’, ‘stable’, ‘sorted’;

end

end

prompt = ‘Press Enter to continue’;

a=input(prompt);

clc();

end

The data entered via the prompt is sent as the second input argument to the unique() function. This input corresponds to the ‘rows’, ‘first’, ‘last’, ‘stable’, ‘sorted’, or ‘legacy’ flags of this function, so it will generate an error if a string is sent that unique() not recognized as one of these flags. It will also generate an error if this input is given a numeric value. We have predefined a case in the switch conditional for each of these two errors to handle each error separately. In both cases, messages are sent to the user informing them of the error and the possible solutions.

When the application is running in the MATLAB console, enter ‘rows’ in the prompt and press Enter. In this case, no error is generated, and the result is = unique(ns, ‘rows’) and is displayed in the command console.

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-136.jpeg" data-lazy- height="879" src="data:image/svg xml,” width=”1280″>

In this case, the string ‘abcd’ was sent to unique(), and since it does not match any of the flags, an error was generated.

In the “catch” block, the information about this error was collected and classified to give it a special treatment, a message to the user with the flag options available in the unique() function.

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-137.jpeg" data-lazy- height="879" src="data:image/svg xml,” width=”1280″>

The same in this case where an input type not accepted was sent, this will generate an error that the “try” block detects and passes control to the “catch” block where the error is classified and treated; in this case, a message to the user reporting the error and the possible solution.

<img data-lazy- data-lazy-src="https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-138.jpeg" data-lazy- height="880" src="data:image/svg xml,” width=”1280″>

Conclusion:

In this article, we have explained the try-catch statement in MATLAB. We also gave some practical examples that demonstrate the use of the “try-catch statement for handling exceptions. We also explained how to classify the errors within the “catch” block using the MException object. We hope you found this MATLAB article useful. See other Linux Hint articles for more tips and information.

About the author

<img alt="" data-lazy-src="https://secure.gravatar.com/avatar/b26dd689ed4af67c9613eb44788137d9?s=112&r=g" data-lazy- height="112" src="data:image/svg xml,” width=”112″>

Julio Cesar

Julio Cesar is a 42 years old programmer with 8 years of experience in embedded systems development, 6 years developing firmware for user interfaces in C and C . Additionally he has 2 years of experience developing scripts for network devices and 3 years as developer of high frequency PCB (Printed Circuit Board).