2016-05-31 69 views
2

我已經覆蓋父方法並在該方法上添加了一個throws聲明。當我添加throws Exceptionthrows FileNotFoundExceprion時,它給了我錯誤,但與throws NullPointerException一起工作。是什麼原因?爲什麼NPE的工作原理,但不是例外和FileNotFoundException

class Vehicle { 
    public void disp() { 
    System.out.println("in Parent"); 
    } 
} 

public class Bike extends Vehicle { 
    public void disp()throws NullPointerException { 
    System.out.println("in Child"); 
    } 

    public static void main(String[] args) { 
    Vehicle v = new Bike(); 
    v.disp(); 
    } 
} 
+6

因爲NullPointerException擴展了RuntimeException並且這不會中斷覆蓋 – Silvinus

+0

當您覆蓋不聲明它拋出它的方法時,不能拋出檢查異常。 – khelwood

+0

不知道你爲什麼被低估。對於不瞭解Java中已檢查和未檢查異常的細節的人來說,這可能會讓人感到困惑。而且我不知道在這種情況下我會弄清楚Google要做什麼。 – sstan

回答

0

概念在Java中有兩種類型的異常:

  • checked異常
  • unchecked異常

這些都是用來表示不同的東西。檢查的異常是可能發生的特殊情況,您不得不處理這種情況。例如,FileNotFoundException是可能出現的情況(例如,您正在嘗試加載尚不存在的文件)。

在這種情況下,這些是檢查,因爲你的程序應該處理它們。

在對面一個未經檢查的異常是不應該在程序的執行過程中,通常會發生的情況,一個NullPointerException意味着你試圖訪問一個null對象,這不應該發生。所以這些例外情況更可能出現在任何地方都可能出現的軟件錯誤中,您不必強制聲明拋出它們並根據需要處理它們是可選的。

按照你的自行車比喻,就像你的Bike職業上有一個FlatTireException。這可能是一個檢查異常,因爲這是一種可能出現的情況,應該處理,而WheelMissingException是不應該發生的事情。

1

NullPointerException是所謂選中異常(因爲它擴展RuntimeException),這意味着你可以在任何地方扔掉它沒有明確標記的方法「拋出」了。相反,您發佈的其他異常是檢查異常,這意味着該方法必須聲明爲「拋出」異常,或者必須在try-catch塊中調用有問題的代碼。例如:

class Vehicle{ 
public void disp() throws Exception { 
    System.out.println("in Parent"); 
} 
} 
public class Bike extends Vehicle { 
public void disp() throws Exception { 
    System.out.println("in Child"); 
} 
public static void main(String[] args) throws Exception { 
    Vehicle v = new Bike(); 
    v.disp(); 
} 
} 

...或:

class Vehicle{ 
public void disp() throws Exception { 
    System.out.println("in Parent"); 
} 
} 
public class Bike extends Vehicle{ 
public void disp() throws Exception { 
    System.out.println("in Child"); 
} 
public static void main(String[] args) { 
    Vehicle v = new Bike(); 
    try { 
     v.disp(); 
    } catch(Exception exception) { 
     // Do something with exception. 
    } 
} 
} 

You can find out more about Java exceptions here.

相關問題