MATLAB - Try...Catch Statement



The try...catch statement in MATLAB is used for handling errors and exceptions that may occur during the execution of your code. It allows you to gracefully handle errors, prevent program crashes, and provide detailed feedback to the user.

Let us check the syntax of try..catch statement.

Syntax

try
   statements
catch exception
   statements
end

The detailed explanation of the syntax is as follows −

Try

The try block is where you have your code enclosed which you feel can generate an error. It's the part of your code that you want to monitor for error exceptions. When MATLAB encounters an error within the try block, it immediately jumps to the corresponding catch block.

Catch Exception

The catch block is where you handle the error that was caught in the try block. It starts with the keyword catch, followed by the variable exception, which can be any valid variable name of your choice. This variable is automatically populated with information about the error that occurred. You can use exceptions to access error-related information, such as the error message, identifier, and more.

The exception variable is optional; you can choose to omit it if you don't need to access information about the error. However, it's commonly used to analyze or log error details.

Statements within Try and Catch

In both the try and catch blocks, you can include one or more MATLAB statements. In the try block, these are the statements where errors might occur. In the catch block, these are the statements you want to execute when an error is caught.

Examples of Try...Catch Statement in MATLAB

Let us see a few examples that show the working of try..catch in matlab.

Example 1: Handling Specific Errors

Let us execute the below code in try...catch block that purposely tries to access an undefined variable −

try
   result = undefined_variable
   fprintf('The result is: %f\n')
catch exception
   fprintf('An error occurred: %s\n', exception.message)
end

When you execute above code in matlab in the output is −

>> try
   result = undefined_variable
   fprintf('The result is: %f\n')
catch exception
   fprintf('An error occurred: %s\n', exception.message)
end

An error occurred: Unrecognized function or variable 'undefined_variable'.

In the code above, accessing undefined_variable is not allowed and will generate an exception, causing the catch block to execute and display an error message indicating that the variable is not defined.

Example 2: Handling Multiple Errors Using Try-catch Block

In this example, the code attempts to access an index that is out of bounds for the array. The catch block handles this specific error, and for other unexpected errors, a different message is displayed.

try
   y = [1, 2, 3];
   z = y(4) % Accessing an out-of-bounds index will generate an error
catch exception
   if strcmp(exception.identifier, 'MATLAB:badsubscript')
      fprintf('Index out of bounds error: %s\n', exception.message);
   else
      fprintf('An unexpected error occurred: %s\n', exception.message);
   end
end

When you execute in Matlab command window the output is −

>> try
   y = [1, 2, 3];
   z = y(4) % Accessing an out-of-bounds index will generate an error
catch exception
   if strcmp(exception.identifier, 'MATLAB:badsubscript')
      fprintf('Index out of bounds error: %s\n', exception.message);
   else
      fprintf('An unexpected error occurred: %s\n', exception.message);
   end
end

Index out of bounds error: Index exceeds the number of array elements. Index must not exceed 3.

Example 3: Another Example Showing Different Types of Errors

This example shows how to handle different types of exceptions using the try...catch construct, where each exception type is examined, and custom warning messages and actions are provided based on the specific exception type, ensuring a graceful response to errors in your code.

try
   result = customFunction(5, 6);
catch exception
   switch exception.identifier
      case 'MATLAB:UndefinedFunction'
         warning('The custom function is not defined. Assigning a value of -1.');
         result = -1;
      case 'MATLAB:scriptNotAFunction'
         warning(['Attempting to execute a script as a function. '...
               'Running the script and assigning the output a value of 0.']);
         customFunctionScript;
         result = 0;
      otherwise
         rethrow(exception)
   end
end

Let us test the same in matlab command window as shown below −

>> try
   result = customFunction(5, 6);
catch exception
   switch exception.identifier
      case 'MATLAB:UndefinedFunction'
         warning('The custom function is not defined. Assigning a value of -1.');
         result = -1;
      case 'MATLAB:scriptNotAFunction'
         warning(['Attempting to execute a script as a function. '...
               'Running the script and assigning the output a value of 0.']);
         customFunctionScript;
         result = 0;
      otherwise
         rethrow(exception)
   end
end

Warning: The custom function is not defined. Assigning a value of -1. 
>> 

Key Points to Remember about Try-Catch Blocks in MATLAB

The detailed explanation of the key points to remember about try-catch blocks in MATLAB is as follows −

Multiple Catch Blocks in a Single Try Block

Unlike programming languages like Java, MATLAB doesn't allow you to have multiple catch blocks within a single try block. In other words, you can't have different catch sections for handling various types of exceptions directly within a try block. Instead, you typically use a single catch block to catch and handle exceptions, and you can then use conditional statements or other logic within that catch block to handle different exception types.

Nesting Try/Catch Blocks

To handle exceptions or to manage different ways of error handling, you can nest complete try/catch blocks. This means you can have a try/catch block within another try/catch block, forming a hierarchy of error-handling mechanisms. This allows you to catch and handle errors at different levels of your code, providing flexibility in error management.

Lack of Finally Blocks

Like other programming languages (e.g., Java), MATLAB does not support the use of a finally block within try/catch statements. A finally block is typically used for code that needs to run regardless of whether an exception occurs or not. In MATLAB, you would need to place such code outside the try/catch block to ensure it always executes, regardless of whether an exception is thrown or not.

Advertisements