gpt4 book ai didi

java - 调试错误 : Exception is never thrown in body of corresponding try statement

转载 作者:行者123 更新时间:2023-11-29 04:37:57 27 4
gpt4 key购买 nike

我有一个我似乎无法理解的类调试任务。我们被告知要调试作业,以便作业的输出看起来像这样。

输出:

There is a problem with the Eagle!
Java Result: 9999

给出的代码如下:

//Superclass for the custom exception.
public class EagleLandingException extends Exception
{
public EagleLandingException(String msg)
{
super(msg);
}
}

和主类

public class ThrowEagleExceptionTest {

public static void main(String[] args) {
try {
EagleLanding();
}
catch (EagleLandingException badEagle) {
System.out.printf("%s\n", badEagle.getMessage());
System.exit(9999);
}
}
private static void EagleLanding () {
EagleLandingException("There is a problem with the Eagle!");
System.exit(9999);
}

我在行中收到“永远不会抛出异常”的错误

catch (EagleLandingException badEagle)

同时在线上收到“找不到符号”错误

EagleLandingException("There is a problem with the Eagle!");

我不明白为什么会这样,并且查看了已经发布的其他问题,但似乎无法弄清楚问题是什么。先感谢您。

最佳答案

问题就在这里

private static void EagleLanding () {
EagleLandingException("There is a problem with the Eagle!");
System.exit(9999);
}

EagleLandingException(...) 被解释为对名为 EagleLandingException 的方法的调用。但这不是一种方法。它是一个构造函数,它的名称(类名)不在 Java 查找方法名称的 namespace 中。编译错误(实际上)是说“我找不到一个名为 ... 的方法”。

另一个问题是您的EagleLanding 方法没有声明为抛出异常。因此,当您随后尝试在调用者中捕获异常时,编译器会说“这是一个已检查的异常,并且由于未将异常声明为已抛出,因此它不会在此处发生”。因此编译错误。

正确的写法是:

private static void eagleLanding () throws EagleLandingException {
throw new EagleLandingException("There is a problem with the Eagle!");
}

注意事项:

  1. new 导致创建异常对象
  2. throw 导致抛出异常。
  3. throws 子句声明该方法抛出已检查的异常。
  4. throw 之后的语句不可访问。如果你不删除它们,你会得到一个编译错误。 (而且,除了在这样的方法中调用 exit 之外,这是一个坏主意......)
  5. 我更改了方法名称以符合 Java 样式规则。方法名称应以小写字母开头。

在他的回答中,@javaguy 建议不要选中 EagleLandingException;即声明为 RuntimeException 的子类型。

这样对吗?也许是,也许不是。在您给我们的(高度人为的)背景下,无法确定。

但是,Java 设计人员建议开发人员应遵循一些通用准则:

  • 已检查的异常适用于预期的事件,在这些事件中可能会对异常采取措施。

  • 未经检查的异常用于意外事件(例如错误),其中(通常)程序员可以做的事情不多。

人们用来决定是使用受检异常还是未受检异常的另一个标准是尽量减少样板代码的数量;即 throws 子句。很多人觉得它们很烦人,会竭尽全力避免它们;例如通过将所有自定义异常声明为未检查、将标准异常包装在自定义异常中等等。

我认为最好的路径介于两者之间。仔细考虑将每个异常声明为已检查或未检查的含义,并使用异常层次结构来管理 throws 声明的大小。

关于java - 调试错误 : Exception is never thrown in body of corresponding try statement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40445311/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com