finally裏面不要拋出異常

class Exception1 extends Exception{
	public Exception1(){
		super("This is Exception1");
	}
}
class Exception2 extends Exception{
	public Exception2(){
		super("This is Exception2");
	}
}
public class Test {
	public static void main(String args[]){
		try {
			testMethod3();
		} catch (Exception1 e) {
			System.out.println(e.getMessage());
		} catch (Exception2 e) {
			System.out.println(e.getMessage());
		}
	}
	public static void testMethod3() throws Exception1, Exception2{
		try {
			System.out.println("1");
			testMethod1(1);
		} catch (Exception1 e) {
			System.out.println("2");
			throw e;
		}finally{
			try {
				System.out.println("3");
				testMethod2(1);
			} catch (Exception2 e) {
				System.out.println("4");
				throw e;
			}
		}
		System.out.println("5");
	}
	public static void testMethod1(int i) throws Exception1{
		if(i==1){
			throw new Exception1();
		}
	}
	public static void testMethod2(int i) throws Exception2{
		if(i==1){
			throw new Exception2();
		}
	}
}

finally裏面不要拋出異常,否則,假如catch語句也拋出了異常,那麼上面一層代碼只能收到finally裏面拋出的異常,而catch拋出的異常將丟失掉。



發佈了44 篇原創文章 · 獲贊 12 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章