Обработка ошибок matlab

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.

function testTryPerformance
x = 1;
for i = 1:1e8
    try
        x = x * i;
    catch
        warning("Assignment was not successful.")
        x = 1;
    end
end
end

The approximate execution times are:

R2021b: 2.3 s

R2022a: 0.4 s

The code was timed on a Windows® 10, Intel®
Xeon® CPU E5-1650 v4 @ 3.60 GHz test system using the
timeit function.

timeit(@testTryPerformance)

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 and catch
    statements.

  • A catch block that includes all lines of code between
    the catch and end 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 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.

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

Выполните операторы и зафиксируйте получившиеся ошибки

Синтаксис

try
   statements
catch exception
   statements
end

Описание

пример

try statements,
catch statements end
выполняет операторы в try блокируйтесь и фиксирует получившиеся ошибки в 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

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    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:

    Matlab

    comb(5,9)    

    function c = comb(n,k)

        c=factorial(n)/(factorial(k)*factorial(n-k));

    end

    Output:

    MATLAB gives following error.

    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:

    Matlab

    n=5

    k=9

    if(n>k)

        comb(n,k)

    else

        comb(k,n)

    end

    function c = comb(n,k)

    c=factorial(n)/(factorial(k)*factorial(n-k));

    end

    Output:

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

    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:

    Matlab

    n=5;

    k=9;

    try

        comb(n,k)

    catch

        comb(k,n)

    end

    function c = comb(n,k)

    c=factorial(n)/(factorial(k)*factorial(n-k));

    end

    Output:

    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.

    Last Updated :
    11 Oct, 2022

    Like Article

    Save Article

    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. 

    Last Updated :
    23 Sep, 2022

    Like Article

    Save Article

    Понравилась статья? Поделить с друзьями:
  • Обработка ошибок vba on error
  • Обработка ошибок json python
  • Обработка ошибок try except
  • Обработка ошибок java spring
  • Обработка ошибок swift