2016-05-31 66 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.

相关问题