1 子類在重寫父類拋出異常的方法時,要么不拋出異常,要么拋出與父類方法相同的異常或該異常的子類。如果被重寫的父類方法只拋出受檢異常,則子類重寫的方法可以拋出非受檢異常。例如,父類方法拋出了一個受檢異常IOException,重寫該方法時不能拋出Exception,對於受檢異常而言,只能拋出IOException及其子類異常,也可以拋出非受檢異常。
舉例如下:
1 class A { 2 public void fun() throws Exception { 3
4 } 5 } 6 class B extends A { 7 public void fun() throws IOException, RuntimeException { 8
9 } 10 }
父類拋出的異常包含所有異常,上面的寫法正確。
1 class A { 2 public void fun() throws RuntimeException { 3
4 } 5 } 6 class B extends A { 7 public void fun() throws IOException, RuntimeException { 8
9 } 10 }
子類IOException超出了父類的異常范疇,上面的寫法錯誤。
1 class A { 2 public void fun() throws IOException { 3
4 } 5 } 6 class B extends A { 7 public void fun() throws IOException, RuntimeException, ArithmeticException { 8
9 } 10 }
RuntimeException不屬於IO的范疇,超出了父類的異常范疇。RuntimeException和ArithmeticException屬於運行時異常,子類重寫的方法可以拋出任何運行時異常。所以上面的寫法正確。
2 子類在重寫父類拋出異常的方法時,如果實現了有相同方法簽名的接口且接口中的該方法也有異常聲明,則子類重寫的方法要么不拋出異常,要么拋出父類中被重寫方法聲明異常與接口中被實現方法聲明異常的交集。
舉例如下:
1 class Test 2 { 3 public Test() throws IOException 4 {} 5 void test() throws IOException 6 {} 7 } 8
9 interface I1{ 10 void test() throw Exception; 11 } 12
13 class SubTest extends Test implements I1 14 { 15 public SubTest() throws Exception,NullPointerException, NoSuchMethodException 16 {} 17 void test() throws IOException 18 {} 19 }
在SubTest類中,test方法要么不拋出異常,要么拋出IOException或其子類(例如,InterruptedIOException)。
參考資料
