谁决定哪些例外被抑制? [英] Who decides what exceptions get suppressed?

查看:159
本文介绍了谁决定哪些例外被抑制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,Java 7的抑制异常功能是一种自动功能。换句话说,在6中的最终块中发生的异常会被自动抑制,有利于资源分配时发生的异常。

As i understand it, Java 7's suppressing exceptions feature is an automatic one. In other words, exceptions happening in what used to be a finally block in 6 are automatically suppressed in favor of exception that took place upon resource allocation.

因此,在此示例中a)打开资源和b)关闭资源或c)可能两者都可能出错。

So, in this example things may go wrong with a) opening a resource and b) closing a resource or c) possibly both.

据我了解,Java 7将抛出异常在打开时,我们可以要求我们给予我们抑制异常,这发生在其他地方。

As i understand it, Java 7 will throw exception that took place upon opening, whom we can ask to give us suppressed exceptions, which took place elsewhere.

    try (BufferedReader inputReader = Files
            .newBufferedReader(Paths.get(new URI(
                    "file:///Users/me/Desktop/readme.txt")), Charset
                    .defaultCharset())) {
        String inputLine;
        while ((inputLine = inputReader.readLine()) != null) {
            System.out.println(inputLine);
        }
    } 

问题是..程序员可以决定什么被压制?毕竟, public addSuppressed()就在那里。

The question is .. Can programmer decide what gets suppressed? After all, public addSuppressed() is there.

请提供示例和用例。

推荐答案

这不是任意的—被抑制的异常会掩盖导致 try <的主要异常/ code>阻止失败—那就是 finally 块中的那些。此功能可确保您获得所有整个构造中抛出的异常,但您捕获的异常将更重要。

This is not arbitrary—the suppressed exceptions are the ones that would otherwise mask the main exception that caused the try block to fail—and that's the ones in the finally block. This feature ensures that you get all the exceptions thrown in the whole construct, but the one you catch will be the more important one.

您不要选择被压制的东西。当然,方法就在那里,否则整个事情都行不通。如果您愿意,可以编写自己的异常处理代码并使用 addSuppressed ad libitum。

You don't get to choose what gets suppressed. The method is there, for sure, otherwise the whole thing wouldn't work. If you like, you can write your own exception handling code and use addSuppressed ad libitum.

这篇关于谁决定哪些例外被抑制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆