gpt4 book ai didi

java - Java 中的致命异常处理

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:20:14 25 4
gpt4 key购买 nike

我正在用 Java 创建一个基本的数学解析器,这样做揭示了我对 Java 异常处理的肤浅理解。

当我有这个输入时:

String mathExpression = "(3+5";

然后我调用:

throw new MissingRightParenException();

IDE 迫使我像这样用 try/catch 包围:

             try {
throw new MissingRightParenException();
} catch (MissingRightParenException e) {
// TODO Auto-generated catch block
e.printStackTrace();

}

但是,为了强制这是一个致命异常,看起来我必须添加自己的代码来调用 System.exit(),如下所示:

             try {
throw new MissingRightParenException();
} catch (MissingRightParenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(0);
}

我不确定我是否理解所有这些背后的语法,尤其是为什么我必须在抛出异常时使用 try/catch block 。

这背后的韵律和原因是什么?

我可以这样做,而不是抛出异常:

new MissingRightParenException();

而不是打电话

throw new MissingRightParenException();

所以我想我的问题是 - 如果这是一个致命异常,那么在为用户提供最佳反馈的同时使其真正致命的最佳方法是什么?

最佳答案

如果您想要一个必须捕获的已检查异常 - 但不是立即捕获 - 那么您可以在方法的签名中定义 throws MissingRightParenException

class MissingRightParenException extends CalculationException {
...
}

class CalculationException extends Exception {
...
}

class MyClass {

int myMathRelatedMethod(String calculation) throws CalculationException {
...
if (somethingWrong) {
throw new MissingRightParenException("Missing right paren for left paren at location: " + location);
}
...
}

public static void main(String ... args) {
...
try {
myMathRelatedMethod(args[0]);
} catch (CalculationException e) {
// stack trace not needed maybe
System.err.println(e.getMessage());
}
...
}
}

您也可以将其定义为 RuntimeException原因,但这似乎不太适合您当前的问题。

try {
...
throw new MissingRightParenException();
...
} catch (MissingRightParenException e) {
// IllegalStateException extends (IS_A) RuntimeException
throw new IllegalStateException("This should never happen", e);
}

如果您的 MissingRightParenException 类扩展了 RuntimeException,那么您不必捕获它。消息将通过所有未明确捕获的方法(或其父类,如 ThrowableExceptionRuntimeException)传递。 然而,您不应将 RuntimeException 用于与输入相关的错误。

通常用户会得到堆栈跟踪或至少是错误消息,当然这取决于线下的错误处理。请注意,即使 main 也不必处理异常。您可以只为 main 方法指定 throws Exception 让控制台接收堆栈跟踪。

所以最后:在你的方法签名中使用 throws 而不是在你想处理它们之前捕获异常。

关于java - Java 中的致命异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28268929/

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