Try and Catch Block in MATLAB
Last Updated :
23 Sep, 2022
Exception Handling is a mechanism used to resolve/handle Runtime errors that arise during the execution of a program. Most programming languages offer some level of exception handling to deal with errors that arise while the program is executing. Exception handling deals with these events to avoid the program or system crashing, and without this process, exceptions would disrupt the normal flow of a program. In MATLAB, this feature is provided in form of try-catch constructs.
In this article, we will learn to incorporate exception handling in MATLAB using the try-catch construct.
Syntax:
try
statements
catch
statements
end
The statements within the try block are executed. If any statement in the try block produces an error, program control goes immediately to the catch block, which contains exception handling statements. If no errors arise during the execution of the try block, the catch block won't be executed. The end keyword is used to denote the end of the try-catch clause (could be used to denote the end of other constructs as well). try-catch blocks could be nested. try-catch statements are useful if
- Want to finish the program in ways that avoid errors.
- Side effects of the error are to be cleaned.
- Have many problematic input parameters or commands.
Try-Catch Usage in MATLAB:
In this example, we would explicitly produce an error (Matlab: UndefinedFunction) within the try block and would respond to it within the catch block.
Example 1:
Matlab
% MATLAB code for try-catch block%
try
fun();
catch
disp("The function is undefined");
end
Output:
The function is undefined
Explanation:
In the above code, we try to call a function named fun within the try block. Since the function hasn't been defined it led to an error. This error got handled by the catch block, leading to the execution of the statements within. This led to "this function is undefined" being displayed in the output, denoting that an error occurred within the try block and the catch block did get executed. If the function was called without placing it within the try block, it would have led to an error and program termination. But since we are using try-catch, this code catches any exception and repackages it as a warning, allowing MATLAB to continue executing subsequent commands.
The above was a very trivial example of the usage of try-catch. But in practice, a way more specific usage of the construct is required. i.e. In the above code, the catch statement would handle any exception produced within the try block whether or not it was required to be resolved or not. This allows certain errors to slip by as everything got handled by the catch statement. So in practice, it is generally advised to mention the error that is required to be handled if it arises. In the subsequent code, we would learn how to determine which error got handled, and to extract information/change the flow of the code based on it.
Example 2:
Matlab
% MATLAB code for try and catch block %
try
fun();
catch ME
% displaying the exception type
disp(ME.identifier);
switch ME.identifier
case 'MATLAB:UndefinedFunction'
disp("Function is undefined");
otherwise
disp("Some other error occurred");
end
end
Output:
MATLAB:UndefinedFunction
Function is undefined
Explanation:
Where the error identifier is displayed at first, then a switch case based on the identifier got executed and displayed Function is undefined. This is because the error that got produced is because of an undefined function. If the error is produced by some other reason (divide by zero, non-matching dimension, etc.) Some other errors that occurred would be displayed along with the identifier of the error.
Similar Reads
Try Catch Block in Programming
In programming, a try catch block is used for exception handling. The try block contains code that might throw an exception and the catch block handles specific exceptions by providing custom code. It prevents program termination when exceptions occur. Remember, we can use a try block without a catc
7 min read
Characters and Strings in MATLAB
In this article, we shall see how to deal with characters and Strings in MATLAB. A data type is an attribute/keyword that specifies the type of data that the object can hold: numeric data or text data. By default, MATLAB stores all numeric variables as double-precision floating-point values. Additio
4 min read
Nested Try Blocks in C++
In C++, a nested try block refers to the try-block nested inside another try or catch block. It is used to handle exceptions in cases where different exceptions occur in a different part of the code. Syntax of Nested Try Blocks The nested try/catch takes this syntax: try { // Code...... throw e2 try
3 min read
Classes and Object in MATLAB
A class is a blueprint that defines the variables and the methods which provide a commonly shared basis for its corresponding objects. It defines an object that encapsulates data and the operations performed on that data. classdef is a keyword used to define MATLAB classes. Syntax to define a class:
4 min read
How to create a function in MATLAB ?
A function is a block of statements that intend to perform a specific task. Functions allow the users to reuse the code frequently. MATLAB has several predefined functions which are ready to use such as sin(), fact(), cos() etc. MATLAB also allows the users to define their own functions. Syntax: fun
2 min read
Scripts and Functions in MATLAB
In MATLAB there are a different kinds of files dedicated to MATLAB codes. They are the following: ScriptLive ScriptFunction only fileClass fileNow only the live script is the only one of these which has a different extension name; all other three use the standard .m extension. In this article, we sh
2 min read
Find() function in MATLAB
The find() function in MATLAB is used to find the indices and values of non-zero elements or the elements which satisfy a given condition. The relational expression can be used in conjunction with find to find the indices of elements that meet the given condition. It returns a vector that contains t
3 min read
How to Add Border an Image in MATLAB?
The border/frame of the image is an outer boundary that is added to the image. It is not part of the main image. Region boundaries and edges are closely related since there is often a sharp adjustment in intensity at the region boundaries. For a grayscale image or any colored image, we can add a bin
3 min read
How to Use & and && Operator in MATLAB?
MATLAB is a high-performance language that is used for matrix manipulation, performing technical computations, graph plottings, etc. It stands for Matrix Laboratory. An operator is a symbol that operates on a value to perform specific mathematical or logical computations. They form the foundation of
3 min read
How To Use | and || Operator in MATLAB?
In MATLAB, | and || are both logical operators that are used to perform logical OR operations on Boolean variables, however, there is a subtle difference between the two: |||Â The element-wise logical OR operator "|" takes two arrays of the same size and returns an array of the same size where each e
4 min read