java - 我们什么时候应该在方法中抛出异常或捕获异常?

标签 java exception exception-handling try-catch

我一直在阅读更多关于异常的内容,但我不确定在什么情况下我们应该抛出一个方法

public void fxml() throws IOException
{
     // method body here
}

或者在方法中捕获异常

public void fxml()
{
          FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("fxml.fxml"));

            try
            {
                fxmlLoader.load();
            } 
            catch (IOException exception) 
            {
                throw new RuntimeException(exception);
            } 
}

从 Oracle 的例子中可以看出

Sometimes, it's appropriate for code to catch exceptions that can occur within it. In other cases, however, it's better to let a method further up the call stack handle the exception. For example, if you were providing the ListOfNumbers class as part of a package of classes, you probably couldn't anticipate the needs of all the users of your package. In this case, it's better to not catch the exception and to allow a method further up the call stack to handle it.

https://docs.oracle.com/javase/tutorial/essential/exceptions/declaring.html

所以我很好奇这是不是说我们可能不需要类/方法,如果我们不使用它,在这个方法中做一个 try/catch 就没有用,所以我们“抛出它”供以后使用?

似乎类本身也会“抛出异常”,以便稍后使用......它只是一个抛出的层次结构,直到你最终可以使用它吗?在上面的教程中,几章之后是一个名为“Chained Exceptions”的章节,这本质上是用于稍后使用的方法 throws 的内容吗?

我也读过这个帖子 When to use throws in a Java method declaration?

但我发现它并没有完全解释我想知道的东西,但是我发现了这个兴趣

If you are catching an exception type, you do not need to throw it, unless you are going to rethrow it. In the example you post, the developer should have done one or another, not both.

Typically, if you are not going to do anything with the exception, you should not catch it.

The most dangerous thing you can do is catch an exception and not do anything with it.

我不太确定他所说的“重新抛出”它是什么意思,除非他说的是抛出该方法并稍后捕获它?

然后他谈到如果您不打算使用它,就不要做任何有异常的事情,所以似乎最好把它扔掉以备后用,以防我们需要它?

然后说它很危险?这是为什么?

所以基本上如果我们不知道我们是否要使用它,那么我们应该抛出它以便调用方法本身,或者如果我们知道它会被调用,无论如何,那么我们应该做一个 try/catch block ?

我还注意到我的示例还抛出了一个基于 IOException 的 RuntimeException。因此,从某种意义上说,您可以采用我们抛出的第一个方法,无论异常如何,然后将其抛入 try OR catch block 中?似乎 catch block 更适合“RuntimeException”或其他系统异常之一,但也许还有其他用例?

想法?

感谢您的帮助!

最佳答案

如果您的代码无法完成其工作(也称为“履行契约(Contract)”),您将抛出异常。发生这种情况的原因可能是调用者向您传递了无效输入,或者某些外部资源出现故障(例如网络连接丢失)。

当下游出现预期的问题且您可以通过某种方式处理时捕获异常。例如,您可能会捕获指示网络问题的异常并重试该操作几次,或者您可能会向用户显示一条错误消息并询问下一步该怎么做。

如果下游代码可能会抛出异常,但您的代码在中间某处并且不知道该怎么做,只需让异常向上传递到调用代码即可。

关于java - 我们什么时候应该在方法中抛出异常或捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33137563/

相关文章:

java - 我可以从 PostgreSQL(在 Heroku 中)中的触发器调用 java 类/方法吗?

java - 并行流是否可以在不同的操作下正常工作?

java - Spring boot应用程序无法启动,可能是数据库连接问题

java - 可以在 JMockit 中模拟用 @Context 注释的字段吗?

c++ - 二维索引异常

javascript - Firefox 不显示自定义错误消息

安卓java.net.SocketException :socket failed: EACCES (Permission denied)

Java异常处理?

java - 在 Java 中处理 IO 异常

Java:处理子线程中的异常