简体   繁体   English

如何检索'try'块中的抑制异常?

[英]how can suppressed exception in the 'try' block be retrieved?

From Java 7, we can use the try-with-resources statement: 从Java 7开始,我们可以使用try-with-resources语句:

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}

if br.readLine() and br.close() both throw exceptions , readFirstLineFromFile will throw the exception from the try block (the exception of br.readLine() ), and the exception from the implicit finally block of the try-with-resources statement (the exception of br.close() ) will be suppressed. 如果br.readLine()br.close() 都抛出异常readFirstLineFromFile将从try块 抛出异常( br.readLine()除外),并且try- br.readLine()隐式finally块中的异常资源语句( br.close()除外)将被禁止。

In this case, we can retrieve suppressed exceptions from the implicit finally block by calling the getSuppresed method from the exception of the try block like this: 在这种情况下,我们可以通过 try块的异常调用getSuppresed方法 隐式finally块中 检索抑制的异常,如下所示:

try {   
    readFirstLineFromFile("Some path here..."); // this is the method using try-with-resources statement
}   catch (IOException e) {     // this is the exception from the try block  
    Throwable[] suppressed = e.getSuppressed();
    for (Throwable t : suppressed) {
        // Check t's type and decide on action to be taken
    }
}

But suppose we have to work with a method written with an older version than Java 7, in which the finally block is used: 但是假设我们必须使用比Java 7更旧的版本编写的方法,其中使用了finally块:

static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }
}

then if br.readLine() and br.close() once again both throw exceptions , the situation will be reversed. 那么如果br.readLine()br.close()再次抛出异常 ,情况将会逆转。 The method readFirstLineFromFileWithFinallyBlock will throw the exception from the finally block (the exception of br.close() ), and the exception from the try block (the exception of br.readLine() ) will be suppressed. 方法readFirstLineFromFileWithFinallyBlock将从finally块中 抛出异常( br.close()除外),并且将禁止try块中的异常( br.readLine()的异常)

So my question here is: how can we retrieve the suppressed exceptions from the try block in the second case? 所以我的问题是:在第二种情况下,如何从try块检索 抑制的异常

Source: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html 资料来源: http//docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

You can't, basically. 基本上你不能。 The suppressed exception is lost if br.close() throws. 如果br.close()抛出, br.close()抑制的异常将丢失。

The closest you could come would be to have a catch block which assigns the value to a locla variable: 你最接近的将是一个catch块,它将值赋给locla变量:

static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
    IOException exception = null;
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
      return br.readLine();
    } catch (IOException e) {
      exception = e;
    } finally {
      try {
        if (br != null) br.close();
      } catch (IOException e) {
        // Both the original call and close failed. Eek!
        // Decide what you want to do here...
      }
      // close succeeded, but we already had an exception
      if (exception != null) {
        throw exception;
      }
    }
}

... but this only handles IOException (rather than any unchecked exceptions) and is horribly messy. ...但是这只处理IOException (而不是任何未经检查的异常)并且非常混乱。

the exception from the try block (the exception of br.readLine() ) will be suppressed. try块的异常(br.readLine()除外)将被禁止。

That's not quite correct. 这不太正确。 The Java Language Specification writes : Java语言规范写道

  • If execution of the try block completes abruptly because of a throw of a value V, then there is a choice: 如果try块的执行由于抛出值V而突然完成,那么有一个选择:

    • If the run-time type of V is not assignment compatible with a catchable exception class of any catch clause of the try statement, then the finally block is executed. 如果V的运行时类型与try语句的任何catch子句的可捕获异常类不兼容,则执行finally块。 Then there is a choice: 然后有一个选择:

      • If the finally block completes normally, then the try statement completes abruptly because of a throw of the value V. 如果finally块正常完成,那么try语句会因为抛出值V而突然完成。

      • If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and the throw of value V is discarded and forgotten). 如果finally块由于原因S而突然完成,则try语句突然完成,原因是S(并且丢弃并抛弃了值V的抛出)。

That is, the exception is "discarded and forgotten", not merely suppressed. 也就是说,例外是“被丢弃和遗忘”,而不仅仅是被压制。

BTW, as the mechanism for attaching a suppressed exception to another exception has been introduced in Java 7, there was no general support for this in Java 6. Therefore, there is no way code targeting Java 6 can make use of that feature. BTW,由于Java 7中引入了将抑制的异常附加到另一个异常的机制 ,因此Java 6中没有对此进行一般性支持。因此,针对Java 6的代码无法使用该功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么try..finally阻止不将原始异常注册为抑制? - Why does try..finally block not register the original exception as suppressed? 在Main函数中,try块引发异常后,如何使其继续执行下一个try块 - In Main function, after a try block throws an exception how can I make it keep on execute the next try block 如何在 try 块内引发异常并终止程序 - How can I throw exception inside the try block and terminate the program 为什么抑制try-with-resource的异常以相反的执行顺序处理? - Why suppressed exception of try-with-resource is handled in a reverse order of execution? 如何在 Try/Catch 块内抛出异常? - How to throw an Exception inside a Try/Catch block? 如果最后跟着try块,如何处理异常 - how to handle exception if finally follows try block 在 try/catch 块捕获异常后如何继续执行代码? - How can I continue executing code after a try/catch block catches an exception? 如何在不引发异常的情况下从 try/catch 块中中断 Java - How can I break from a try/catch block without throwing an exception in Java 如何在一个try / catch块中捕获异常和SocketTimeOut异常 - How to catch an Exception and a SocketTimeOut Exception in one try/catch block 我们可以在try块中获取LineNumber和ColumnNumber,发生异常 - Can we get LineNumber and ColumnNumber in try block at which exception occured
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM