我重写了来自父方法的一个方法,并在该方法上添加了一个throws声明。当我添加throws Exception和throws FileNotFoundExceprion但使用throws NullPointerException时,它给我带来了错误。原因何在?
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();
}
}发布于 2016-05-31 14:25:00
从概念上讲,Java有两种类型的例外:
这些用来表示不同的东西。检查异常是一种特殊的情况,它可能会发生,而您不得不处理这个问题。例如,FileNotFoundException是一种可能出现的情况(例如,您正在尝试加载一个尚不存在的文件)。
在这种情况下,会检查它们,因为您的程序应该处理它们。
另一方面,未经检查的异常是在程序执行过程中通常不应该发生的情况,NullPointerException意味着您试图访问null对象,而这种情况不应该发生。因此,这些异常更有可能是软件中可能出现的错误,您不会被迫声明抛出它们的内容,并且根据需求处理它们是可选的。
通过你的自行车类比,这就像在你的Bike类上有一个Bike。这可能是一个检查异常,因为它可能会出现,应该处理,而WheelMissingException是不应该发生的事情。
发布于 2016-05-31 14:18:52
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();
}
}...or:
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.
}
}
}https://stackoverflow.com/questions/37548145
复制相似问题