【问题标题】:Why NPE works but not Exception and FileNotFoundException [duplicate]为什么 NPE 有效但 Exception 和 FileNotFoundException 无效 [重复]
【发布时间】:2016-05-31 14:12:43
【问题描述】:

我已经覆盖了父方法并在该方法上添加了throws 声明。当我添加 throws Exceptionthrows 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();
  }
}

【问题讨论】:

  • 因为 NullPointerException 扩展了 RuntimeException 并且这不会破坏覆盖
  • 当你重写一个没有声明它抛出它的方法时,你不能抛出一个检查异常。
  • 不知道为什么你被否决了。对于不了解 Java 中已检查异常与未检查异常的微妙之处的人来说,这可能会非常令人困惑。而且我不知道在这种情况下我会弄清楚用谷歌搜索什么。
  • 这也意味着您不需要输入throws NullPointerException,即使您在方法中添加了一个。 RuntimeExceptions 用于不可恢复的错误,通常是未经检查的。
  • @sstan 可能是因为“它给了我一个错误”

标签: java exception nullpointerexception


【解决方案1】:

NullPointerException 是一个所谓的unchecked 异常(因为它扩展了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.

【讨论】:

    【解决方案2】:

    从概念上讲,Java 中有两种类型的异常:

    • 检查的异常
    • 未经检查的异常

    这些用于表示不同的事物。已检查异常是一种可能发生的特殊情况,您必须处理这种情况。例如,FileNotFoundException 是一种可能出现的情况(例如,您正在尝试加载一个尚不存在的文件)。

    在这种情况下,这些是选中的,因为你的程序应该处理它们。

    另一方面,未经检查的异常是在程序执行期间通常不应该发生的情况,NullPointerException 表示您正在尝试访问 null 对象,这不应该永远发生。所以这些异常更有可能是软件中可能出现的错误,你不必强制声明是什么引发了它们,并且根据要求处理它们是可选的。

    按照您的自行车类比,这就像在您的 Bike 班级上有一个 FlatTireException。它可能是一个检查异常,因为它是一种可能出现并且应该处理的情况,而 WheelMissingException 是不应该发生的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-18
      • 2020-06-17
      • 2022-01-12
      • 2020-05-14
      • 2020-10-07
      • 2023-03-30
      相关资源
      最近更新 更多