Overview
The MATLAB® software, by default, terminates the currently running program when an
exception is thrown. If you catch the exception in your program, however, you can
capture information about what went wrong and deal with the situation in a way that
is appropriate for the particular condition. This requires a
try/catch
statement.
The try/catch Statement
When you have statements in your code that could generate undesirable results, put
those statements into a try/catch
block that catches any errors
and handles them appropriately.
A try/catch
statement looks something like the following
pseudocode. It consists of two parts:
-
A
try
block that includes all lines between the
try
andcatch
statements. -
A
catch
block that includes all lines of code between
thecatch
andend
statements.
try Perform one ... or more operations A catch ME Examine error info in exception object ME Attempt to figure out what went wrong Either attempt to recover, or clean up and abort end B Program continues
The program executes the statements in the try
block. If it
encounters an error, it skips any remaining statements in the
try
block and jumps to the start of the
catch
block (shown here as point A
). If
all operations in the try
block succeed, then execution skips
the catch
block entirely and goes to the first line following
the end
statement (point B
).
Specifying the try
, catch
, and
end
commands and also the code of the
try
and catch
blocks on separate lines is
recommended. If you combine any of these components on the same line, separate them
with commas:
try, surf, catch ME, ME.stack, end
ans =
file: 'matlabroottoolboxmatlabgraph3dsurf.m'
name: 'surf'
line: 49
Note
You cannot define nested functions within a try
or
catch
block.
The Try Block
On execution, your code enters the try
block and executes
each statement as if it were part of the regular program. If no errors are
encountered, MATLAB skips the catch
block entirely and continues
execution following the end
statement. If any of the
try
statements fail, MATLAB immediately exits the try
block, leaving any
remaining statements in that block unexecuted, and enters the
catch
block.
The Catch Block
The catch
command marks the start of a
catch
block and provides access to a data structure that
contains information about what caused the exception. This is shown as the
variable ME
in the preceding pseudocode.
ME
is an MException
object. When an
exception occurs, MATLAB creates an MException
object and returns it in
the catch
statement that handles that error.
You are not required to specify any argument with the catch
statement. If you do not need any of the information or methods provided by the
MException
object, just specify the
catch
keyword alone.
The MException
object is constructed by internal code in
the program that fails. The object has properties that contain information about
the error that can be useful in determining what happened and how to proceed.
The MException
object also provides access to methods that
enable you to respond to the exception.
Having entered the catch
block, MATLAB executes the statements in sequence. These statements can attempt
to
-
Attempt to resolve the error.
-
Capture more information about the error.
-
Switch on information found in the
MException
object and respond appropriately. -
Clean up the environment that was left by the failing code.
The catch
block often ends with a
rethrow
command. The rethrow
causes MATLAB to exit the current function, keeping the call stack information
as it was when the exception was first thrown. If this function is at the
highest level, that is, it was not called by another function, the program
terminates. If the failing function was called by another function, it returns
to that function. Program execution continues to return to higher level
functions, unless any of these calls were made within a higher-level
try
block, in which case the program executes the
respective catch block.
Suggestions on How to Handle an Exception
The following example reads the contents of an image file. It includes detailed
error handling, and demonstrates some suggested actions you can take in response to
an error.
The image-reading function throws and catches errors in several ways.
-
The first
if
statement checks whether the function is
called with an input argument. If no input argument is specified, the
program throws an error and suggests an input argument to correct the
error. -
The
try
block attempts to open and read the file. If
either the open or the read fails, the program catches the resulting
exception and saves theMException
object in the variable
ME1
. -
The
catch
block checks to see if the specified file
could not be found. If so, the program allows for the possibility that a
common variation of the filename extension (e.g.,jpeg
instead ofjpg
) was used, by retrying the operation with
a modified extension. This is done using atry/catch
statement nested within the originaltry/catch
.
function d_in = read_image(filename) % Check the number of input arguments. if nargin < 1 me = MException('MATLAB:notEnoughInputs','Not enough input arguments.'); aac = matlab.lang.correction.AppendArgumentsCorrection('"image.png"'); me = me.addCorrection(aac); throw(me); end % Attempt to read file and catch an exception if it arises. try fid = fopen(filename,'r'); d_in = fread(fid); catch ME1 % Get last segment of the error identifier. idSegLast = regexp(ME1.identifier,'(?<=:)w+$','match'); % Did the read fail because the file could not be found? if strcmp(idSegLast,'InvalidFid') && ... ~exist(filename,'file') % Yes. Try modifying the filename extension. switch ext case '.jpg' % Change jpg to jpeg filename = strrep(filename,'.jpg','.jpeg'); case '.jpeg' % Change jpeg to jpg filename = strrep(filename,'.jpeg','.jpg'); case '.tif' % Change tif to tiff filename = strrep(filename,'.tif','.tiff'); case '.tiff' % Change tiff to tif filename = strrep(filename,'.tiff','.tif'); otherwise fprintf('File %s not foundn',filename); rethrow(ME1); end % Try again, with modified filenames. try fid = fopen(filename,'r'); d_in = fread(fid); catch ME2 fprintf('Unable to access file %sn',filename); ME2 = addCause(ME2,ME1); rethrow(ME2) end end end
This example illustrates some of the actions that you can take in response to an
exception.
-
Compare the
identifier
field of the
MException
object to possible causes of the error. In
this case, the function checks whether the identifier ends in
'InvalidFid'
, indicating a file could not be
found. -
Use a nested
try/catch
statement to retry the operation
with improved input. In this case, the function retries the open and read
operations using a known variation of the filename extension. -
Display an appropriate message.
-
Add the first
MException
object to the
cause
field of the second. -
Add a suggested correction to an
MException
object. -
Rethrow the exception. This stops program execution and displays the error
message.
Cleaning up any unwanted results of the error is also advisable. For example,
close figures that remained open after the error occurred.
try, catch
Выполните операторы и зафиксируйте получившиеся ошибки
Синтаксис
trystatements
catchexception
statements
end
Описание
пример
try
выполняет операторы в statements
,
catch statements
endtry
блокируйтесь и фиксирует получившиеся ошибки в catch
блок. Этот подход позволяет вам заменять ошибочное поведение по умолчанию для набора операторов программы. Если любой оператор в try
блок генерирует ошибку, программное управление сразу переходит к catch
блокируйтесь, который содержит ваши операторы обработки ошибок.
exception
MException
объект, который позволяет вам идентифицировать ошибку. catch
блок присваивает текущий объект исключения переменной в exception
.
Оба try
и catch
блоки могут содержать, вложил try/catch
операторы.
Примеры
свернуть все
Добавление сообщения об ошибке
Создайте две матрицы, которые вы не можете конкатенировать вертикально.
A = rand(3); B = ones(5); C = [A; B];
Error using vertcat Dimensions of matrices being concatenated are not consistent.
Используйте try/catch
отобразить больше информации о размерностях.
try C = [A; B]; catch ME if (strcmp(ME.identifier,'MATLAB:catenate:dimensionMismatch')) msg = ['Dimension mismatch occurred: First argument has ', ... num2str(size(A,2)),' columns while second has ', ... num2str(size(B,2)),' columns.']; causeException = MException('MATLAB:myCode:dimensions',msg); ME = addCause(ME,causeException); end rethrow(ME) end
Error using vertcat Dimensions of matrices being concatenated are not consistent. Caused by: Dimension mismatch occurred: First argument has 3 columns while second has 5 columns.
Если матричные размерности не соглашаются, MATLAB® отображения больше информации о несоответствии. Любые другие ошибки появляются, как обычно.
Ошибка перепакета как предупреждение
Отловите любое исключение, сгенерированное путем вызывания несуществующей функции, notaFunction
. Если существует исключение, выдайте предупреждение и присвойте выход значение 0.
try a = notaFunction(5,6); catch warning('Problem using function. Assigning a value of 0.'); a = 0; end
Warning: Problem using function. Assigning a value of 0.
Отдельно, вызов notaFunction
результаты по ошибке. Если вы используете try
и catch
, этот код отлавливает любое исключение и повторно группирует его как предупреждение, позволяя MATLAB продолжить выполнять последующие команды.
Обработка различных типов ошибок
Используйте try/catch
обрабатывать различные типы ошибок по-разному.
-
Если функциональный
notaFunction
не определено, выдайте предупреждение вместо ошибки и присвойте выход значениеNaN
. -
Если
notaFunction.m
существует, но скрипт вместо функции, выдайте предупреждение вместо ошибки, запустите скрипт и присвойте выход значение0
. -
Если MATLAB выдает ошибку по какой-либо другой причине, повторно выдайте исключение.
try a = notaFunction(5,6); catch ME switch ME.identifier case 'MATLAB:UndefinedFunction' warning('Function is undefined. Assigning a value of NaN.'); a = NaN; case 'MATLAB:scriptNotAFunction' warning(['Attempting to execute script as function. '... 'Running script and assigning output a value of 0.']); notaFunction; a = 0; otherwise rethrow(ME) end end
Warning: Function is undefined. Assigning a value of NaN.
Советы
-
Вы не можете использовать несколько
catch
блоки вtry
блокируйтесь, но можно вложить полныйtry/catch
блоки. -
В отличие от некоторых других языков, MATLAB не позволяет использование
finally
блокируйтесь вtry/catch
операторы.
Представлено до R2006a
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
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
try
fun();
catch
ME
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.
Содержание
- try , catch
- Syntax
- Description
- Examples
- Supplement Error Message
- Repackage Error as Warning
- Handle Different Types of Errors
- Extended Capabilities
- Thread-Based Environment Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool .
- Version History
- R2022a: Improved performance when statements run error-free
- try , catch
- Syntax
- Description
- Examples
- Supplement Error Message
- Repackage Error as Warning
- Handle Different Types of Errors
- Extended Capabilities
- Thread-Based Environment Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool .
- Version History
- R2022a: Improved performance when statements run error-free
- error
- Syntax
- Description
- Examples
- Throw Error
- Throw Error with Formatted Message
- Throw Error Using Structure
- Throw Error with Suggested Fix
- Input Arguments
- msg — Information about error text scalar containing format specification
- errID — Identifier for error text scalar containing component and mnemonic fields
- A1. An — Values character vector | string scalar | numeric scalar
- errorStruct — Error reporting information scalar structure
- correction — Suggested fix for this exception matlab.lang.correction.AppendArgumentsCorrection object | matlab.lang.correction.ConvertToFunctionNotationCorrection object | matlab.lang.correction.ReplaceIdentifierCorrection object
- Extended Capabilities
- C/C++ Code Generation Generate C and C++ code using MATLAB® Coder™.
- Thread-Based Environment Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool .
- GPU Arrays Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
- Error Handling
- MATLAB Language Syntax
- Functions
- Topics
- Matlab if error occurs
- The try/catch Statement
- The Try Block
- The Catch Block
- Suggestions on How to Handle an Exception
- MATLAB Command
try , catch
Execute statements and catch resulting errors
Syntax
Description
try statements , catch statements end executes the statements in the try block and catches resulting errors in the catch block. This approach allows you to override the default error behavior for a set of program statements. If any statement in a try block generates an error, program control goes immediately to the catch block, which contains your error handling statements.
exception is an MException object that allows you to identify the error. The catch block assigns the current exception object to the variable in exception .
Both try and catch blocks can contain nested try/catch statements.
Examples
Supplement Error Message
Create two matrices that you cannot concatenate vertically.
Use try/catch to display more information about the dimensions.
If matrix dimensions do not agree, MATLAB ® displays more information about the mismatch. Any other errors appear as usual.
Repackage Error as Warning
Catch any exception generated by calling the nonexistent function, notaFunction . If there is an exception, issue a warning and assign the output a value of 0.
By itself, the call to notaFunction results in an error. If you use try and catch , this code catches any exception and repackages it as a warning, allowing MATLAB to continue executing subsequent commands.
Handle Different Types of Errors
Use try/catch to handle different types of errors in different ways.
If the function notaFunction is undefined, issue a warning instead of an error and assign the output a value of NaN .
If notaFunction.m exists, but is a script instead of a function, issue a warning instead of an error, run the script, and assign the output a value of 0 .
If MATLAB throws an error for any other reason, rethrow the exception.
You cannot use multiple catch blocks within a try block, but you can nest complete try/catch blocks.
Unlike some other languages, MATLAB does not allow the use of a finally block within try/catch statements.
Extended Capabilities
Thread-Based Environment
Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool .
This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
Version History
R2022a: Improved performance when statements run error-free
The try block shows improved performance when the statements within the block run error-free. For example, this code is approximately 6x faster than in the previous release.
The approximate execution times are:
The code was timed on a Windows ® 10, Intel ® Xeon ® CPU E5-1650 v4 @ 3.60 GHz test system using the timeit function.
Источник
try , catch
Execute statements and catch resulting errors
Syntax
Description
try statements , catch statements end executes the statements in the try block and catches resulting errors in the catch block. This approach allows you to override the default error behavior for a set of program statements. If any statement in a try block generates an error, program control goes immediately to the catch block, which contains your error handling statements.
exception is an MException object that allows you to identify the error. The catch block assigns the current exception object to the variable in exception .
Both try and catch blocks can contain nested try/catch statements.
Examples
Supplement Error Message
Create two matrices that you cannot concatenate vertically.
Use try/catch to display more information about the dimensions.
If matrix dimensions do not agree, MATLAB ® displays more information about the mismatch. Any other errors appear as usual.
Repackage Error as Warning
Catch any exception generated by calling the nonexistent function, notaFunction . If there is an exception, issue a warning and assign the output a value of 0.
By itself, the call to notaFunction results in an error. If you use try and catch , this code catches any exception and repackages it as a warning, allowing MATLAB to continue executing subsequent commands.
Handle Different Types of Errors
Use try/catch to handle different types of errors in different ways.
If the function notaFunction is undefined, issue a warning instead of an error and assign the output a value of NaN .
If notaFunction.m exists, but is a script instead of a function, issue a warning instead of an error, run the script, and assign the output a value of 0 .
If MATLAB throws an error for any other reason, rethrow the exception.
You cannot use multiple catch blocks within a try block, but you can nest complete try/catch blocks.
Unlike some other languages, MATLAB does not allow the use of a finally block within try/catch statements.
Extended Capabilities
Thread-Based Environment
Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool .
This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
Version History
R2022a: Improved performance when statements run error-free
The try block shows improved performance when the statements within the block run error-free. For example, this code is approximately 6x faster than in the previous release.
The approximate execution times are:
The code was timed on a Windows ® 10, Intel ® Xeon ® CPU E5-1650 v4 @ 3.60 GHz test system using the timeit function.
Источник
error
Throw error and display message
Syntax
Description
error( msg ) throws an error and displays an error message.
error( msg , A1. An ) displays an error message that contains formatting conversion characters, such as those used with the MATLAB ® sprintf function. Each conversion character in msg is converted to one of the values A1. An .
error( errID , ___ ) includes an error identifier on the exception. The identifier enables you to distinguish errors and to control what happens when MATLAB encounters the errors. You can include any of the input arguments in the previous syntaxes.
error( errorStruct ) throws an error using the fields in a scalar structure.
error( correction , ___ ) provides a suggested fix for the exception. You can include any of the input arguments in the previous syntaxes.
Examples
Throw Error
Throw Error with Formatted Message
Throw a formatted error message with a line break. You must specify more than one input argument with error if you want MATLAB to convert special characters (such as n ) in the error message. Include information about the class of variable n in the error message.
If you only use one input argument with error , then MATLAB does not convert n to a line break.
Throw an error with an identifier.
Use the MException.last to view the last uncaught exception.
Throw Error Using Structure
Create structure with message and identifier fields. To keep the example simple, do not use the stack field.
Throw the error.
Throw Error with Suggested Fix
Create a function hello that requires one input argument. Add a suggested input argument «world» to the error message.
Call the function without an argument.
Input Arguments
msg — Information about error
text scalar containing format specification
Information about the error, specified as a text scalar containing format specification. This message displays as the error message. To format the message, use escape sequences, such as t or n . You also can use any format specifiers supported by the sprintf function, such as %s or %d . Specify values for the conversion specifiers via the A1. An input arguments. For more information, see Formatting Text.
Note
You must specify more than one input argument with error if you want MATLAB to convert special characters (such as t , n , %s , and %d ) in the error message.
Example: ‘File not found.’
errID — Identifier for error
text scalar containing component and mnemonic fields
Identifier for the error, specified as a text scalar containing component and mnemonic fields. Use the error identifier to help identify the source of the error or to control a selected subset of the errors in your program.
The error identifier includes one or more component fields and a mnemonic field. Fields must be separated with colon. For example, an error identifier with a component field component and a mnemonic field mnemonic is specified as ‘component:mnemonic’ . The component and mnemonic fields must each begin with a letter. The remaining characters can be alphanumerics (A–Z, a–z, 0–9) and underscores. No white-space characters can appear anywhere in errID . For more information, see MException .
Example: ‘MATLAB:singularMatrix’
Example: ‘MATLAB:narginchk:notEnoughInputs’
A1. An — Values
character vector | string scalar | numeric scalar
Values that replace the conversion specifiers in msg , specified as a character vector, string scalar, or numeric scalar.
errorStruct — Error reporting information
scalar structure
Error reporting information, specified as a scalar structure. The structure must contain at least one of these fields.
Error message. For more information, see msg .
Error identifier. For more information, see errID .
Stack field for the error. When errorStruct includes a stack field, error uses it to set the stack field of the error. When you specify stack , use the absolute file name and the entire sequence of functions that nests the function in the stack frame. This character vector is the same as the one returned by dbstack(‘-completenames’) .
correction — Suggested fix for this exception
matlab.lang.correction.AppendArgumentsCorrection object | matlab.lang.correction.ConvertToFunctionNotationCorrection object | matlab.lang.correction.ReplaceIdentifierCorrection object
When you throw an error, MATLAB captures information about it and stores it in a data structure that is an object of the MException class. You can access information in the exception object by using try/catch . Or, if your program terminates because of an exception and returns control to the Command Prompt, you can use MException.last .
MATLAB does not cease execution of a program if an error occurs within a try block. In this case, MATLAB passes control to the catch block.
If all inputs to error are empty, MATLAB does not throw an error.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
Has no effect in standalone code even when run-time error detection is enabled. See Generate Standalone C/C++ Code That Detects and Reports Run-Time Errors (MATLAB Coder) .
Thread-Based Environment
Run code in the background using MATLAB® backgroundPool or accelerate code with Parallel Computing Toolbox™ ThreadPool .
This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
Usage notes and limitations:
This function accepts GPU arrays, but does not run on a GPU.
For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox) .
Источник
Error Handling
To make your code more robust, check for edge cases and problematic conditions. The simplest approach is to use an if or switch statement to check for a specific condition, and then issue an error or warning. try/catch statements allow you to catch and respond to any error.
MATLAB Language Syntax
try, catch | Execute statements and catch resulting errors |
Functions
error | Throw error and display message |
warning | Display warning message |
lastwarn | Last warning message |
assert | Throw error if condition false |
onCleanup | Cleanup tasks upon function completion |
Topics
To flag unexpected conditions when running a program, issue a warning. To flag fatal problems within the program, throw an error. Unlike warnings, errors halt the execution of a program.
Your program might issue warnings that do not always adversely affect execution. To avoid confusion, you can hide warning messages during execution by changing their states from ‘on’ to ‘off’ .
You can save the warning current states, modify warning states, and restore the original warning states. This technique is useful if you temporarily turn off some warnings and later reinstate the original settings.
You can control how warnings appear in MATLAB ® , including the display of warning suppression information and stack traces.
Use a try/catch statement to execute code after your program encounters an error.
It is a good programming practice to leave your program environment in a clean state that does not interfere with any other program code.
Источник
Matlab if error occurs
The MATLAB ® software, by default, terminates the currently running program when an exception is thrown. If you catch the exception in your program, however, you can capture information about what went wrong and deal with the situation in a way that is appropriate for the particular condition. This requires a try/catch statement.
The try/catch Statement
When you have statements in your code that could generate undesirable results, put those statements into a try/catch block that catches any errors and handles them appropriately.
A try/catch statement looks something like the following pseudocode. It consists of two parts:
A try block that includes all lines between the try and catch statements.
A catch block that includes all lines of code between the catch and end statements.
The program executes the statements in the try block. If it encounters an error, it skips any remaining statements in the try block and jumps to the start of the catch block (shown here as point A ). If all operations in the try block succeed, then execution skips the catch block entirely and goes to the first line following the end statement (point B ).
Specifying the try , catch , and end commands and also the code of the try and catch blocks on separate lines is recommended. If you combine any of these components on the same line, separate them with commas:
Note
You cannot define nested functions within a try or catch block.
The Try Block
On execution, your code enters the try block and executes each statement as if it were part of the regular program. If no errors are encountered, MATLAB skips the catch block entirely and continues execution following the end statement. If any of the try statements fail, MATLAB immediately exits the try block, leaving any remaining statements in that block unexecuted, and enters the catch block.
The Catch Block
The catch command marks the start of a catch block and provides access to a data structure that contains information about what caused the exception. This is shown as the variable ME in the preceding pseudocode. ME is an MException object. When an exception occurs, MATLAB creates an MException object and returns it in the catch statement that handles that error.
You are not required to specify any argument with the catch statement. If you do not need any of the information or methods provided by the MException object, just specify the catch keyword alone.
The MException object is constructed by internal code in the program that fails. The object has properties that contain information about the error that can be useful in determining what happened and how to proceed. The MException object also provides access to methods that enable you to respond to the exception.
Having entered the catch block, MATLAB executes the statements in sequence. These statements can attempt to
Attempt to resolve the error.
Capture more information about the error.
Switch on information found in the MException object and respond appropriately.
Clean up the environment that was left by the failing code.
The catch block often ends with a rethrow command. The rethrow causes MATLAB to exit the current function, keeping the call stack information as it was when the exception was first thrown. If this function is at the highest level, that is, it was not called by another function, the program terminates. If the failing function was called by another function, it returns to that function. Program execution continues to return to higher level functions, unless any of these calls were made within a higher-level try block, in which case the program executes the respective catch block.
Suggestions on How to Handle an Exception
The following example reads the contents of an image file. It includes detailed error handling, and demonstrates some suggested actions you can take in response to an error.
The image-reading function throws and catches errors in several ways.
The first if statement checks whether the function is called with an input argument. If no input argument is specified, the program throws an error and suggests an input argument to correct the error.
The try block attempts to open and read the file. If either the open or the read fails, the program catches the resulting exception and saves the MException object in the variable ME1 .
The catch block checks to see if the specified file could not be found. If so, the program allows for the possibility that a common variation of the filename extension (e.g., jpeg instead of jpg ) was used, by retrying the operation with a modified extension. This is done using a try/catch statement nested within the original try/catch .
This example illustrates some of the actions that you can take in response to an exception.
Compare the identifier field of the MException object to possible causes of the error. In this case, the function checks whether the identifier ends in ‘InvalidFid’ , indicating a file could not be found.
Use a nested try/catch statement to retry the operation with improved input. In this case, the function retries the open and read operations using a known variation of the filename extension.
Display an appropriate message.
Add the first MException object to the cause field of the second.
Add a suggested correction to an MException object.
Rethrow the exception. This stops program execution and displays the error message.
Cleaning up any unwanted results of the error is also advisable. For example, close figures that remained open after the error occurred.
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Источник
The following article explains how to use the try-catch statement in MATLAB®. The try-catch instruction is one of the most widely used programming languages globally, and its execution mode is the same for all of them. This article includes practical examples and images to help the reader understand how to use this statement to handle errors in real-time execution.
MATLAB try catch Syntax
try
statements
catch exception
statements
end
MATLAB try catch descriptions and examples
A try-catch statement is a tool that gives the program stability and robustness against exceptions or errors in real execution time. These exceptions or errors can be caught so that when one of these events occurs, they can be handled in a predictable and orderly manner and do not affect system performance.
The try-catch statement consists of two blocks: try is the block that encloses the part of the code that can generate an exception or error, and the catch is the block that handles these exceptions to be safely processed. When a try catches an exception, it passes control to catch for processing. Below, we will look at some practical examples using the try-catch statement to understand better how it works.
How to detect and process an exception or error with the try-catch statement in MATLAB
This example shows how to use the try-catch statement against a common error when calculating square roots with the realsqrt() function. This is one of the three basic functions MATLAB has for this type of mathematical operation, and it only accepts real numbers with a positive sign as input arguments. If this rule is not satisfied, an error is generated.
<img data-lazy- data-lazy-src=»https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-133.jpeg» data-lazy- height=»755″ src=»data:image/svg xml,” width=”1440″>
Next, let us look at detecting and handling this error by creating a console application that calculates square roots using the realsqrt() function. This operation is performed in the try block. When an error occurs, control is passed to catch to resolve the calculation using the sqrt() function, which accepts negative or complex numbers.
Create a script, paste this code, and click Run. To close the application, press Ctrl c
while 1
prompt = ‘Enter a value to get its square root.’;
a=input(prompt);
try
x =realsqrt(a);
catch
disp ‘Try found an error and passed the control to catch’
x=sqrt(a);
end
disp([‘The square root is: ‘, num2str(x)])
end
Once the app is up and running, we enter the values we need to calculate the square root.
If negative or complex values are entered, instead of raising an error in the realsqrt() function, it will pass control to catch, and the operation is resolved with the sqrt() function. When this happens, the following message is displayed in the command console:
“Try to find an error and passed the control to catch”
<img data-lazy- data-lazy-src=»https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-134.jpeg» data-lazy- height=»757″ src=»data:image/svg xml,” width=”1440″>
How to identify errors with “MException” and manage them with try catch in MATLAB
Although identifying exceptions with “MException” deserves its own article, we will briefly explain how to use this resource, which helps us identify errors and is an effective complement when using the try-catch statement. MATLAB constructs a “MException” object with information about the error when an error is generated. This information is very useful as we can use it to classify and handle various specific errors. Below you can see the contents of “MException” with information about an error generated by the unique() function.
<img data-lazy- data-lazy-src=»https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-135.jpeg» data-lazy- height=»881″ src=»data:image/svg xml,” width=”1280″>
In the following example, we will see how to retrieve this information to process the errors correctly. To do this, we will create a console application in which we will use the unique() function to generate the errors that we will handle in the catch block and the prompt() function to input the data that will be the input arguments of unique().
When a try catches one of these errors, it stores its information in the “MException”, which we will create with the name “inf_err”, as shown below.
In the catch block, we send a message to the user informing them of detecting an error with the following message “Try has found an error and passed control to catch”.
Then we take the error identifier from the previously created object “err_inf.identifier”. This identifier has the form of a string and gives us information about:
The function that generated it MATLAB:UNIQUE
And the specific error UnknownInput
‘MATLAB:UNIQUE:UnknownInput’
This string will be the argument that the switch conditional will compare with each of the predefined errors in each case.
switch inf_err.identifier
case ‘MATLAB:UNIQUE:UnknownInput’
……
case ‘MATLAB:UNIQUE:UnknownFlag’
……
end
A possible solution to the error or a message to the user will be given in each case.
Create a script, paste this code and run the script. To close the application, press Ctrl C.
ns= [1, 2, 3; 4, 5, 6];
while 1
prompt = ‘Enter a value to get unique.’;
a=input(prompt);
try
x=unique(ns, a);
catch inf_err
disp ‘Try found an error and passed the control to catch’;
disp ([ ‘Error identifier :’ ,inf_err.identifier]);
switch inf_err.identifier
case ‘MATLAB:UNIQUE:UnknownInput’
disp ‘The specified entry could not be found. Please try again.’;
case ‘MATLAB:UNIQUE:UnknownFlag’
disp ‘The unique() function does not recognize the flag:’;
disp(a);
disp ‘Valid flags are ‘rows’, ‘first’, ‘last’, ‘stable’, ‘sorted’;
end
end
prompt = ‘Press Enter to continue’;
a=input(prompt);
clc();
end
The data entered via the prompt is sent as the second input argument to the unique() function. This input corresponds to the ‘rows’, ‘first’, ‘last’, ‘stable’, ‘sorted’, or ‘legacy’ flags of this function, so it will generate an error if a string is sent that unique() not recognized as one of these flags. It will also generate an error if this input is given a numeric value. We have predefined a case in the switch conditional for each of these two errors to handle each error separately. In both cases, messages are sent to the user informing them of the error and the possible solutions.
When the application is running in the MATLAB console, enter ‘rows’ in the prompt and press Enter. In this case, no error is generated, and the result is = unique(ns, ‘rows’) and is displayed in the command console.
<img data-lazy- data-lazy-src=»https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-136.jpeg» data-lazy- height=»879″ src=»data:image/svg xml,” width=”1280″>
In this case, the string ‘abcd’ was sent to unique(), and since it does not match any of the flags, an error was generated.
In the “catch” block, the information about this error was collected and classified to give it a special treatment, a message to the user with the flag options available in the unique() function.
<img data-lazy- data-lazy-src=»https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-137.jpeg» data-lazy- height=»879″ src=»data:image/svg xml,” width=”1280″>
The same in this case where an input type not accepted was sent, this will generate an error that the “try” block detects and passes control to the “catch” block where the error is classified and treated; in this case, a message to the user reporting the error and the possible solution.
<img data-lazy- data-lazy-src=»https://kirelos.com/wp-content/uploads/2022/04/echo/word-image-138.jpeg» data-lazy- height=»880″ src=»data:image/svg xml,” width=”1280″>
Conclusion:
In this article, we have explained the try-catch statement in MATLAB. We also gave some practical examples that demonstrate the use of the “try-catch statement for handling exceptions. We also explained how to classify the errors within the “catch” block using the MException object. We hope you found this MATLAB article useful. See other Linux Hint articles for more tips and information.
This note briefly discusses how to deal with exceptions in MATLAB. An exception is an event which occurs during the execution of a program and disrupts the normal flow of the program’s instructions. The process to deal with such exceptional events in the program is called Exception handling.
What is exception handling
Good code has to be able to handle exceptional (rare) situations that may occur during the code execution. These exceptions may occur during data input from either command line, terminal window, or an input file. They may also occur as a result of repeated operations on the input data, inside the code. For example, division by zero is an exceptional event in the program that any professionally-written program should be able to catch and handle nicely. Another example can be found in the discussion of data-transfer methods, where we explained a way of handling a wrong number of input command-line arguments. This and similar measures to handle the unexpected runtime situations that could lead to errors nicely is called exception handling.
Exception vs. error:
There is a distinction between an exceptional situation in a program and an error that is often recognized: In general, an error indicates the occurrence of a serious condition in the code that is unrecoverable. If it happens, it crashes the code. On the other hand, an exception indicates the occurrence of an event which, if not properly taken care of, could lead to a runtime error.
A simple way of error handling is to write multiple if-blocks each of which handles a specific exceptional situation. In other words, let the code execute some statements, and if something goes wrong, write the program in such a way that it can detect this and jump to a set of statements that handle the erroneous situation as desired.
The try/catch
statement
A more modern and flexible way of handling such potential exceptions in MATLAB is through MATLAB’s try/catch construction. You can use a try/catch statement to execute code after your program encounters an exception. The try/catch
statements can be useful when,
- you Want to finish the program in another way that avoids errors (which could lead to abrupt interruption of the program) or,
- you want to nicely control the effects of error (for example, when a division by zero happens in your calculations) or,
- you have a function that could take many problematic parameters or commands as input.
The general syntax for try/catch statements is like the following pseudocode,
try
try statements (all the normal things you would want to do)...
catch exception
catch block (things to do when the try statements go wrong) ...
end
If an exception occurs within the try block, MATLAB skips any remaining commands in the try block and executes the commands in the catch block. If no error occurs within the try-block, MATLAB skips the entire catch block.
For example, suppose we wanted to read data from a webpage that does not exist,
>> webContent = webread('https://www.cdslab.org/non-existing-page.html')
Error using readContentFromWebService (line 45)
The server returned the status 404 with message "Not Found" in response to the request to URL https://www.cdslab.org/non-existing-page.html.
Error in webread (line 125)
[varargout{1:nargout}] = readContentFromWebService(connection, options);
In such cases, it would be nice to control the behavior of the problem, and not allow MATLAB to end the program abruptly. We could therefore say,
>> try
webContent = webread('https://www.cdslab.org/non-existing-page.html')
catch
disp('The requested page does not exist! Gracefully exiting...')
end
The requested page does not exist! Gracefully exiting...
MATLAB define some functions that are used to control error. The try-catch statement is an error control function, which is explained below.
Try-catch statement provides error handling control. General form of the try-catch statement is
Syntax:
try
Statements
catch exception
Statements
end
Statements between try and catch execute first. If no error appears in executing statements between try and catch, MATLAB further executes the statements/code after the end keyword. If an error occurs during the execution of statements between try and catch, MATLAB executes statements between catch and end. Try-catch statement can be explained with the help of the following example.
Example:
a = ones(4);
b = zeros(3);
try
c = [a;b];
catch ME
disp(ME)
end
Output:
MException with properties:
identifier: 'MATLAB:catenate:dimensionMismatch'
message: 'Dimensions of arrays being concatenated are not consistent.'
cause: {0×1 cell}
stack: [3×1 struct]
Correction: []
Following are the points while using a try/catch statement in MATLAB:
- The control of the program execution first enters the try block and executes each statement.
- If any error occurs during the execution, then the control immediately passes to the catch block, leaving any other statements of the try block unexecuted.
- If there is no error occurs inside try block, then the control doesn’t enter the catch block. The control then reaches to the statements after the end keyword of try/ catch block.
- Whenever any error or exception occurs in the try block, the MATLAB constructs an instance of the MException class and returns the object in the catch statement.
- The MException class object can be accessed with the variable ME.
- The MException class object has five properties-identifier, message, stack, cause, and Correction. These properties describe details about the occurred exception.
- We can’t use multiple catch block, only one catch block within a try block is allowed.
- We can use nested try/catch blocks if required.
Example showing MException class object properties:
a = ones(4);
b = zeros(3);
try
c = [a;b];
catch ME
% strcmp string compare function, to check the same string in ME identifier
if (strcmp(ME.identifier,'MATLAB:catenate:dimensionMismatch'))
% if it is true then change the message property
msg = ['dimension mismatch occured: First argument has ',...
num2str(size(a,2)), ' columns, while second argument has ',...
num2str(size(b,2)),' columns.'];
causeException = MException('MATLAB:mycode:dimensions',msg)
ME = addCause(ME, causeException);
end
end
Output:
causeException =
MException with properties:
identifier: 'MATLAB:mycode:dimensions'
message: 'dimension mismatch occured: First argument has 4 columns, while second argument has 3 columns.'
cause: {}
stack: [0×1 struct]
Correction: []
Program Termination
Program termination control allows to exit from our program at some point before its normal termination point.