matlab报错语句,MATLAB错误控制语句try-catch
本⽂概述
MATLAB定义了⼀些⽤于控制错误的函数。 try-catch语句是⼀个错误控制功能, 下⾯将对其进⾏说明。
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语句的要点:
程序执⾏的控制⾸先进⼊try块并执⾏每个语句。
如果在执⾏过程中发⽣任何错误, 则控件将⽴即传递到catch块, ⽽try块的任何其他语句均未执⾏。
如果try块内没有发⽣错误, 则控件不会进⼊catch块。然后控件到达try / catch块的end关键字之后的语句。
每当try块中发⽣任何错误或异常时, MATLAB都会构造MException类的实例, 并在catch语句中返回该对象。
可以使⽤变量ME访问MException类对象。
MException类对象具有五个属性标识, 消息, 堆栈, 原因和更正。这些属性描述有关发⽣的异常的详细信息。
我们不能使⽤多个catch块, 只能在try块中使⽤⼀个catch块。
如果需要, 我们可以使⽤嵌套的try / catch块。
显⽰MException类对象属性的⽰例:
a = ones(4);
b = zeros(3);
try catch的使用方法
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: []
程序终⽌
程序终⽌控制允许在正常终⽌点之前的某个时刻退出我们的程序。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。