我想运行几行代码,但我不确定是否有任何行会抛出错误。如果发生错误,我希望脚本忽略该行并继续。顺序尝试捕捉结束块的matlab
一个选择是有一个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
相关:Why should I not wrap every block in "try"-"catch"?
我可以想出解决这个问题的递归方法,但这可能不是最优雅的方式...... – user2305193
您可以通过不重新抛出错误来继续其余代码。你可以发布[mcve]吗? – beaker
即使您不重新抛出错误,“catch”分支的其余部分也会被跳过。例如见'clear,a = 1; c = 3;尝试,显示(a),显示(b),显示(c),结束' –