Обработка ошибок матлаб

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)

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

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

    Понравилась статья? Поделить с друзьями:
  • Обработка ошибок компилятором
  • Обработка ошибок исключения python
  • Обработка ошибок джанго
  • Обработка ошибок postgresql golang
  • Обработка ошибок джава