MATLAB - Error Handling



Error handling is a way that allows you to manage and respond to errors or unexpected situations that might occur while your MATLAB program is running. Instead of letting your program crash and give unnecessary results, you can gracefully handle errors, provide feedback to the user, and even attempt to recover from the issue.

The most common type of errors that can occur while executing the code are syntax errors, runtime errors, or logical errors.

Syntax Errors

A syntax error in MATLAB occurs when there is a mistake in the structure or syntax of your code.

Example

% Syntax Error Example
c = a + b;

In this code, there's a syntax error because a and b are not defined or assigned any values before they are used in the calculation. MATLAB expects these variables to be defined or assigned values before they can be used in expressions. To correct this syntax error, you should define or assign values to a and b before using them.

Runtime Errors

A runtime error in MATLAB occurs when your code is running, but it encounters a problem during execution that prevents it from completing successfully.

result = 10 / 0; % Division by zero

Attempting to divide a number by zero results in a runtime error.

Logical Errors

% Logical Error Example
n = 5;
sum = 0;
for i = 1:n
   sum = sum + i;
end

In this code, the loop runs from 1 to n, adding the values from 1 to n to sum. However, if we want to calculate the sum of numbers from 1 to n, the code is incorrect because it will include n in the sum. The loop should be running from 1 to n-1.

Error handling in matlab helps us to take care of the syntax, runtime and logical issues if any while executing the code. Error handling will tell the correct reason for any failure of executing the code to the user.

Display Error Message to Users in Matlab

Heres a simple example of how to use display error message to users in matlab −

Syntax

error(msg) : helps to generate a simple error message with a custom explanation
error(msg,A) : helps to create an error message with placeholders (e.g., %s, %d) that can be replaced with actual values from variables.

Example 1: Using error(msg)

value = 120;
if value > 100
   error('Value entered is greater than expected. Please use a smaller value.');
end

In this example, if the value is greater than 100, it will trigger the error with the custom message "Value entered is greater than expected. Please use a smaller value."

On execution inside matlab command window the output is −

>> value = 120;
if value > 100
   error('Value entered is greater than expected. Please use a smaller value.');
end

error: Value entered is greater than expected. Please use a smaller value.

Example 2: Using error(msg, A)

age = 150;
if age > 100
   error('Error: Age value is too high. It should be below %d.', 100);
end

In this example, if age is greater than 100, the error message will include the value 100 in place of the %d placeholder, resulting in the message: "Error: Age value is too high. It should be below 100."

On execution inside matlab command window the output is −

>> age = 150;
if age > 100
    error('Error: Age value is too high. It should be below %d.', 100);
end

error: Age value is too high. It should be below 100.

Display Warning Message to Users in Matlab

For warning messages we can make use of the warning() in-built function available in matlab.

warning(msg) : used to issue a warning with a custom message msg.
warning(msg,A) : displays message containing format conversion characters, similar to the ones used in MATLAB sprintf() function.Every placeholder character within the 'msg' is substituted with one of the corresponding values from 'A'.
warning(state): enables, disables, or displays the status of all warnings.

Example 1

In the example below a warning message saying: "The value of x (10) is larger than 5." wil be displayed. The %d is a formatting character, and the value of x gets inserted into the warning message at that position.

x = 10;
if x > 5
   warning('The value of x (%d) is larger than 5.', x);
end

On execution in matlab command window the output is −

>> x = 10;
if x > 5
   warning('The value of x (%d) is larger than 5.', x);
end

Warning: The value of x (10) is larger than 5.

Example 2

Let us use warning() method to just display the warning message as shown in the example below −

warning('Testing warning!')

On execution in matlab command window the output is −

>> warning('Testing warning!')

Warning: Testing warning! 

Example 3

To know the status of the warning you can just type warning and enter in the matlab command window.

warning

On execution in matlab command window the output is −

>> warning
All warnings have the state 'on'.

Example 4

warning('off')

Once you execute the above code and type warning , you should see the message All warnings have the state 'off'.

>> warning('off')
>> warning
All warnings have the state 'off'.

Example 5

warning('on')

Once you execute the above code and type warning , you should see the message All warnings have the state 'on'.

>> warning('on')
>> warning
All warnings have the state 'on'.

Error Handling with try/catch Statements

The try and catch blocks in MATLAB help manage potential errors that may occur during code execution.

Example of try/catch

The example shows code that attempts to execute the test() function inside the try block. If an error occurs during the execution of test(), MATLAB will catch the error and jump to the catch block, where it displays an error message that includes details about the error using disp(['Error occurred: ' exception.message]);

try
   a = test()
catch exception
   % Handle the error here
   disp(['Error occurred: ' exception.message]);
end

When you execute the same in matlab command window the output is −

>> try
   a = test()
catch exception
   % Handle the error here
   disp(['Error occurred: ' exception.message]);
end
Error occurred: Execution of script test as a function is not supported:
/MATLAB Drive/test.m

If you see the execution, the function test is not present hence the error is caught and the detailed error message is displayed.

Advertisements