Matlab的顺序尝试捕获端块 [英] sequential try catch end block for matlab

查看:58
本文介绍了Matlab的顺序尝试捕获端块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想运行几行代码,但是我不确定是否有任何一行会抛出错误.但是,如果发生错误,我希望脚本忽略该行并继续.

I'd like to run several lines of code, but I'm unsure if any line will throw an error. If an error occurs however, I'd like the script to ignore that line and continue on.

一种选择是拥有一个try-catch-end块,该块会跳过可能引发错误的代码块.但是,一旦发生错误,try语句中错误之后的其余代码将不会执行.

One choice would be to have a try-catch-end block, that skips over a block of code that may throw errors. However, as soon as an error occurs, the rest of the code after the error in the try-statement is not executed.

TL; TR:除了在下面的示例代码中为每行写一个try-catch-end块之外,我还有别的选择吗?

TL;TR: Do I have another choice than writing a try-catch-end block for every individual line in the following example code?

示例代码:

try
  disp('1st line');
  disp('2nd line');
  PRODUCE_ERROR;  %throws an error, variable/function does not exist
  disp('3rd line'); %%%%%
  disp('4th line'); % these lines I would like to keep executing
  disp('5th line'); %%%%%
catch
  disp('something unexpected happened');
end

输出:

1st line
2nd line
something unexpected happened

首选输出:

1st line
2nd line
something unexpected happened
3rd line
4th line
5th line

相关:为什么我应该不是在"try"-"catch"中包装每个块?

推荐答案

一种选择是将代码的每个部分放入函数中,并在匿名函数的列表的示例:

One option is to put each section of code in a function and iterate over a cell array of the function handles. Here's an example with a list of anonymous functions:

fcnList = {@() disp('1'); ...
           @() disp('2'); ...
           @() error(); ...    % Third function throws an error
           @() disp('4')};

for fcnIndex = 1:numel(fcnList)
  try
    fcnList{fcnIndex}();  % Evaluate each function
  catch
    fprintf('Error with function %d.\n', fcnIndex);  % Display when an error happens
  end
end

这是生成的输出,显示即使在抛出错误后,函数仍会被求值:

And here's the output this generates, showing that functions are still evaluated even after one throws an error:

1
2
Error with function 3.
4

上面的示例适用于您有单个行想要顺序评估的代码的情况,但是您无法将多个行放入匿名函数中.在这种情况下,我会使用嵌套函数,如果它们必须访问较大工作空间中的变量或局部函数他们可以独立运作.这是带有嵌套函数的示例:

The above example works for the case when you have individual lines of code you want to evaluate sequentially, but you can't fit multiple lines into an anonymous function. In this case, I would go with nested functions if they have to access variables in the larger workspace or local functions if they can operate independently. Here's an example with nested functions:

function fcn1
  b = a+1;     % Increments a
  fprintf('%d\n', b);
end
function fcn2
  error();     % Errors
end
function fcn3
  b = a.^2;    % Squares a
  fprintf('%d\n', b);
end

a = 2;
fcnList = {@fcn1 @fcn2 @fcn3};

for fcnIndex = 1:numel(fcnList)
  try
    fcnList{fcnIndex}();
  catch
    fprintf('Error with function %d.\n', fcnIndex);
  end
end

输出:

3
Error with function 2.
4

这篇关于Matlab的顺序尝试捕获端块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆