【发布时间】:2017-09-14 15:24:54
【问题描述】:
我想运行几行代码,但我不确定是否有任何行会引发错误。但是,如果发生错误,我希望脚本忽略该行并继续。
一种选择是使用try-catch-end 块,它会跳过可能引发错误的代码块。但是,一旦发生错误,try-statement 中错误之后的其余代码都不会执行。
TL;TR:除了为以下示例代码中的每一行编写一个 try-catch-end 块之外,我还有其他选择吗?
示例代码:
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
【问题讨论】:
-
我可以想到递归的方法来解决这个问题,但这可能不是最优雅的方法......
-
您可以通过不重新抛出错误来继续执行其余代码。可以发minimal reproducible example吗?
-
即使不重新抛出错误,
catch分支的其余部分也会被跳过。参见例如clear, a = 1; c = 3; try, disp(a), disp(b), disp(c), end -
@beaker: 更新代码
-
@LuisMendo 是的,您仍然需要遍历 try/catch 块。