Tag Archives: try … catch

The use of try… Catch in MATLAB

The use of try… Catch in MATLAB

In the design of MATLAB program, if we can’t ensure whether a certain program code will make mistakes, we can use try… Catch statement, which can capture and handle errors, so that the possible error code will not affect the subsequent code execution, and can also check

Check, solve some errors of the program, enhance the robustness and reliability of the code

Format:

try

Program code 1

catch

Program code 2

end

First, the program runs “code 1” between try and catch. If there is no error, it does not execute “code 2” between catch and end, but executes the program after end; If an error occurs when executing “program code 1”, execute “program code 2” immediately, and then continue to execute the program after end

For example:

1、try…end

Try… End is used to try to run a piece of code that may go wrong, such as:

m = rand(3,4);

n = magic(5);

try

a = m*n;

disp(a)

end

disp(m)

In this code, a = m * n will run in error, which does not meet the principle of matrix multiplication. Therefore, a = m * N and disp (a) will not be executed, but the subsequent disp (m) will also be executed;

2、try…catch…end

m = rand(3,4);

n = magic(5);

try

a = m*n;

disp(a)

catch err

disp(size(m))

disp(size(n))

end

disp(m)

Here, when the program encounters a = m * n; After the error, it will jump to the statement in the catch and continue to execute, which is similar to if… Else… End;

The addition of err enables it to clearly display the line where debugging is running

Copyright notice: This article is the original article of the blogger and cannot be reproduced without the permission of the blogger. https://blog.csdn.net/wangrenbao123/article/details/55252242