Error Handling in MATLAB (original) (raw)
Last Updated : 28 Apr, 2025
Error Handling is the approach of creating a program that handles the exceptions thrown by different conditions without crashing the program. For example, consider the case when you are multiplying two matrices of orders (m x n) and (m x n). Now, anyone who has done elementary linear algebra knows that this multiplication is not feasible because the number of columns in matrix 1 is not equal to the number of rows in matrix 2. Computers are also aware of the same fact and any programming language will through an Error/Exception in this scenario. To avoid crashing of the program, the programmer inserts a condition that checks for the same scenario. This is error handling. Now we will see how Error Handling is done in MATLAB.
Using if-else Ladder:
A trivial way of handling errors is by using the if-else conditional. Consider the following example, where we create a function to calculate the combination of two positive integers. Now, the only error possible in this function is when k>n. So, let us see how MATLAB responds to the case.
Example 1:
Matlab `
% MATLAB code for Error Handling % using If-else ladder
comb(5,9)
% keeping n<k
%function function c = comb(n,k) c=factorial(n)/(factorial(k)*factorial(n-k)); end
`
Output:
MATLAB gives following error.

To avoid this error, we can simply insert an if-else conditional to check whether k<n or not. If not then, the program will calculate the combination of (k, n).
Example 2:
Matlab `
% MATLAB code for error handling n=5 k=9
% Conditional if(n>k) comb(n,k) else comb(k,n) end
%function function c = comb(n,k) c=factorial(n)/(factorial(k)*factorial(n-k)); end
`
Output:
This will calculate the combination of (9,5):

The Try-Catch Blocks:
A better approach for doing the same is by using the try-catch block. Try block takes the statements that might throw an error/exception and when encountered, all the remaining statements are skipped, and the program moves to the catch block for the handled error/exception.
Example 3:
Matlab `
% MATLAB code for Try-Catch Blocks n=5; k=9;
% Try block to handle the exception try comb(n,k) catch comb(k,n) end
% Function function c = comb(n,k) c=factorial(n)/(factorial(k)*factorial(n-k)); end
`
Output:

The benefit of using try-catch block over the if-else conditional is that the latter can only handle exceptions which are known before compilation. On the other hand, try-catch can handle exceptions that are not known in advanced.