我想運行幾行代碼,但我不確定是否有任何行會拋出錯誤。如果發生錯誤,我希望腳本忽略該行並繼續。順序嘗試捕捉結束塊的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),結束' –