VOOZH about

URL: https://www.geeksforgeeks.org/matlab/error-handling-in-matlab/

⇱ Error Handling in MATLAB - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Error Handling in MATLAB

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:

Output:

MATLAB gives following error.

👁 Image
 

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:

Output:

This will calculate the combination of (9,5):

👁 Image
 

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:

Output:

👁 Image
 

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.

Comment