
- 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 - 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.