1. 程式人生 > >try-catch和throw,throws的區別

try-catch和throw,throws的區別

參考文章

throw跟try...catch...finally的對比:

public class ZeroTest {
	public static void main(String[] args) {
		try {
			int i = 100 / 0;
			System.out.print(i);
		} catch (Exception e) {
			System.out.print(1);
			throw new RuntimeException();
		} finally {
			System.out.print(2);
		}
		System.out.print(3);
	}
}

try catch是直接處理,處理完成之後程式繼續往下執行,throw則是將異常拋給它的上一級處理,程式便不往下執行了。 本題的catch語句塊裡面,列印完1之後,又丟擲了一個RuntimeException,程式並沒有處理它,而是直接丟擲,因此執行完finally語句塊之後,程式終止了。執行結果12。首先執行try,遇到算術異常,丟擲,執行catch,列印1,然後丟擲RuntimeException,快取異常,執行finally,列印2,然後丟擲RuntimeException。如果catch中沒有丟擲RuntimeException,則執行結果為123。