2014-01-05 21 views
1

所以我是Java新手,我嘗試使用try,catch和finally特性。由於我的理解有限,try-catch塊允許我處理異常,而不是編譯器拋出一個我無法返回執行的錯誤。這是正確的嗎?另外,我的程序似乎沒有工作,因爲編譯器會拋出「Extracur是抽象的,無法實例化!」編譯期間。我怎樣才能讓它顯示我的錯誤信息(並執行我的finally塊)呢?嘗試在JAVA中處理InstantiationException,編譯器會拋出它而不是

try { 
     extracur student1 = new extracur(); 
    } catch (InstantiationException e) { 
     System.out.println("\n Did you just try to create an object for an interface? Tsk tsk."); 
    } finally { 
     ReportCard student = new ReportCard("Progress Report for the year 2012-13"); 
     student.printReportCard(); 
    } 

PS-extracur是一個接口。

+1

try/catch塊是一類在那裏捕獲運行時異常 - 運行一個程序,你需要編譯它 - 編譯錯誤需要修復程序編譯... – assylias

+0

啊。這就說得通了!非常感謝! –

回答

0

接口永遠不能直接實例化。

extracur student1=new extracur(); // not possible 

而且您應該大寫接口名稱。您需要改爲:

Extracur student1 = new Extracur() { 
    // implement your methods 
}; 

說明:代碼沒有實例化接口,而是實現接口的匿名內部類。

您還應該理解,在嘗試在運行時捕獲錯誤(在這種情況下太晚)時,編譯器會引發錯誤。

+0

會不會,謝謝!然而,我一直在想,爲什麼每個人都在Java中使用駱駝大小寫和大寫?當我學習C和C++時,沒有人堅持。任何特定的原因? –

+0

這是Java中常用的命名約定,用於在啓動變量和方法名稱時始終使用小寫字母來使類和接口名稱大寫。它提高了可讀性和可理解性。 –

0

接口不能instantiated.It會導致編譯error.If你想。嘗試這樣一個測試:

try { 
      extracur student1 = new stud(); 
     } catch (InstantiationException e) { 
      System.out 
        .println("\n Did you just try to create an object for an interface? Tsk tsk."); 
     } finally { 

     } 

這是impements接口extracur

class stud implements extracur{ 
    public stud()throws InstantiationException{ 
     throw new InstantiationException(); 
    } 
} 
相關問題