首頁 > Java > java教程 > 主體

在Java中覆蓋時,父子層次結構對於拋出異常重要嗎?

WBOY
發布: 2023-08-19 13:49:23
轉載
1254 人瀏覽過

在Java中覆蓋時,父子層次結構對於拋出異常重要嗎?

當您嘗試處理由特定方法拋出的(已檢查的)異常時,您需要使用Exception類別或發生異常的超類別來捕獲它。

同樣,在重寫超類別的方法時,如果它拋出異常−

  • #子類別中的方法應該拋出相同的異常或其子類型。

  • 子類別中的方法不應該拋出其超類型。

  • 您可以在不拋出任何例外的情況下進行重寫。

當您有三個名為Demo,SuperTest和Super的類別(層次結構)繼承時,如果Demo和SuperTest有一個名為sample()的方法。

範例

 即時示範

class Demo {
   public void sample() throws ArrayIndexOutOfBoundsException {
      System.out.println("sample() method of the Demo class");
   }
}
class SuperTest extends Demo {
   public void sample() throws IndexOutOfBoundsException {
      System.out.println("sample() method of the SuperTest class");
   }
}
public class Test extends SuperTest {
   public static void main(String args[]) {
      Demo obj = new SuperTest();
      try {
         obj.sample();
      }catch (ArrayIndexOutOfBoundsException ex) {
         System.out.println("Exception");
      }
   }
}
登入後複製

輸出

sample() method of the SuperTest class
登入後複製

如果你捕捉異常的類別與拋出的異常不相同或不是異常的超類,你將會得到一個編譯時錯誤。

同樣地,在重寫方法時,拋出的異常應該與被重寫方法拋出的異常相同或是其超類,否則會發生編譯時錯誤。

範例

 示範

import java.io.IOException;
import java.io.EOFException;
class Demo {
   public void sample() throws IOException {
      System.out.println("sample() method of the Demo class");
   }
}
class SuperTest extends Demo {
   public void sample() throws EOFException {
      System.out.println("sample() method of the SuperTest class");
   }
}
public class Test extends SuperTest {
   public static void main(String args[]) {
      Demo obj = new SuperTest();
      try {
         obj.sample();
      }catch (EOFException ex){
         System.out.println("Exception");
      }
   }
}
登入後複製

輸出

Test.java:12: error: sample() in SuperTest cannot override sample() in Demo
public void sample() throws IOException {
            ^
overridden method does not throw IOException
1 error

D:\>javac Test.java
Test.java:20: error: unreported exception IOException; must be caught or declared to be thrown
   obj.sample();
              ^
1 error
登入後複製

以上是在Java中覆蓋時,父子層次結構對於拋出異常重要嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!