1. 程式人生 > >try-catch遇到循環時,將try代碼塊放在循環內還是循環外的選擇

try-catch遇到循環時,將try代碼塊放在循環內還是循環外的選擇

cep sage for runt exception string image row ring

當循環內的代碼出現異常,需要結束循環時,將try代碼塊放在循環外;

當循環內的代碼出現異常,需要繼續執行循環時,將try代碼塊放在循環內

	public static void main(String[] args) {
		int runs = 3; //循環運行次數

		//try代碼塊在循環外
		try {
			for (int i = 0; i < runs; i++) {
				if (i == 0) {
					throw new RuntimeException("try在循環外時,出現運行異常");
				}
				System.out.println("do something...");
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

		System.out.println("--------------------------");

		//try代碼塊在循環內
		for (int i = 0; i < runs; i++) {
			try {
				if (i == 0) {
					throw new RuntimeException("try在循環內時,出現運行異常");
				}
				System.out.println("do something...");
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
		}
	}

  技術分享圖片

try-catch遇到循環時,將try代碼塊放在循環內還是循環外的選擇