📅  最后修改于: 2021-01-07 02:19:58             🧑  作者: Mango
MATLAB定义了一些用于控制错误的函数。 try-catch语句是一个错误控制函数,下面将对其进行说明。
try-catch语句提供错误处理控制。 try-catch语句的一般形式是
句法:
try
Statements
catch exception
Statements
end
try和catch之间的语句首先执行。如果在try和catch之间执行语句时未出现错误,则MATLAB会在end关键字之后进一步执行语句/代码。如果在try和catch之间执行语句期间发生错误,则MATLAB将在catch和end之间执行语句。 try-catch语句可以在以下示例的帮助下进行解释。
例:
a = ones(4);
b = zeros(3);
try
c = [a;b];
catch ME
disp(ME)
end
输出:
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: []
以下是在MATLAB中使用try / catch语句的要点:
显示MException类对象属性的示例:
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
输出:
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: []
程序终止控制允许在正常终止点之前的某个时刻退出程序。