
- MATLAB - Home
- MATLAB - Overview
- MATLAB - Features
- MATLAB - Environment Setup
- MATLAB - Editors
- MATLAB - Online
- MATLAB - Workspace
- MATLAB - Syntax
- MATLAB - Variables
- MATLAB - Commands
- MATLAB - Data Types
- MATLAB - Operators
- MATLAB - Dates and Time
- MATLAB - Numbers
- MATLAB - Random Numbers
- MATLAB - Strings and Characters
- MATLAB - Text Formatting
- MATLAB - Timetables
- MATLAB - M-Files
- MATLAB - Colon Notation
- MATLAB - Data Import
- MATLAB - Data Output
- MATLAB - Normalize Data
- MATLAB - Predefined Variables
- MATLAB - Decision Making
- MATLAB - Decisions
- MATLAB - If End Statement
- MATLAB - If Else Statement
- MATLAB - If…Elseif Else Statement
- MATLAB - Nest If Statememt
- MATLAB - Switch Statement
- MATLAB - Nested Switch
- MATLAB - Loops
- MATLAB - Loops
- MATLAB - For Loop
- MATLAB - While Loop
- MATLAB - Nested Loops
- MATLAB - Break Statement
- MATLAB - Continue Statement
- MATLAB - End Statement
- MATLAB - Arrays
- MATLAB - Arrays
- MATLAB - Vectors
- MATLAB - Transpose Operator
- MATLAB - Array Indexing
- MATLAB - Multi-Dimensional Array
- MATLAB - Compatible Arrays
- MATLAB - Categorical Arrays
- MATLAB - Cell Arrays
- MATLAB - Matrix
- MATLAB - Sparse Matrix
- MATLAB - Tables
- MATLAB - Structures
- MATLAB - Array Multiplication
- MATLAB - Array Division
- MATLAB - Array Functions
- MATLAB - Functions
- MATLAB - Functions
- MATLAB - Function Arguments
- MATLAB - Anonymous Functions
- MATLAB - Nested Functions
- MATLAB - Return Statement
- MATLAB - Void Function
- MATLAB - Local Functions
- MATLAB - Global Variables
- MATLAB - Function Handles
- MATLAB - Filter Function
- MATLAB - Factorial
- MATLAB - Private Functions
- MATLAB - Sub-functions
- MATLAB - Recursive Functions
- MATLAB - Function Precedence Order
- MATLAB - Map Function
- MATLAB - Mean Function
- MATLAB - End Function
- MATLAB - Error Handling
- MATLAB - Error Handling
- MATLAB - Try...Catch statement
- MATLAB - Debugging
- MATLAB - Plotting
- MATLAB - Plotting
- MATLAB - Plot Arrays
- MATLAB - Plot Vectors
- MATLAB - Bar Graph
- MATLAB - Histograms
- MATLAB - Graphics
- MATLAB - 2D Line Plot
- MATLAB - 3D Plots
- MATLAB - Formatting a Plot
- MATLAB - Logarithmic Axes Plots
- MATLAB - Plotting Error Bars
- MATLAB - Plot a 3D Contour
- MATLAB - Polar Plots
- MATLAB - Scatter Plots
- MATLAB - Plot Expression or Function
- MATLAB - Draw Rectangle
- MATLAB - Plot Spectrogram
- MATLAB - Plot Mesh Surface
- MATLAB - Plot Sine Wave
- MATLAB - Interpolation
- MATLAB - Interpolation
- MATLAB - Linear Interpolation
- MATLAB - 2D Array Interpolation
- MATLAB - 3D Array Interpolation
- MATLAB - Polynomials
- MATLAB - Polynomials
- MATLAB - Polynomial Addition
- MATLAB - Polynomial Multiplication
- MATLAB - Polynomial Division
- MATLAB - Derivatives of Polynomials
- MATLAB - Transformation
- MATLAB - Transforms
- MATLAB - Laplace Transform
- MATLAB - Laplacian Filter
- MATLAB - Laplacian of Gaussian Filter
- MATLAB - Inverse Fourier transform
- MATLAB - Fourier Transform
- MATLAB - Fast Fourier Transform
- MATLAB - 2-D Inverse Cosine Transform
- MATLAB - Add Legend to Axes
- MATLAB - Object Oriented
- MATLAB - Object Oriented Programming
- MATLAB - Classes and Object
- MATLAB - Functions Overloading
- MATLAB - Operator Overloading
- MATLAB - User-Defined Classes
- MATLAB - Copy Objects
- MATLAB - Algebra
- MATLAB - Linear Algebra
- MATLAB - Gauss Elimination
- MATLAB - Gauss-Jordan Elimination
- MATLAB - Reduced Row Echelon Form
- MATLAB - Eigenvalues and Eigenvectors
- MATLAB - Integration
- MATLAB - Integration
- MATLAB - Double Integral
- MATLAB - Trapezoidal Rule
- MATLAB - Simpson's Rule
- MATLAB - Miscellenous
- MATLAB - Calculus
- MATLAB - Differential
- MATLAB - Inverse of Matrix
- MATLAB - GNU Octave
- MATLAB - Simulink
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.