有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Trywithresources:我必须抛出或捕获close()方法的异常吗?

如果这是错误的,请纠正我:在Java 7的try with resources语句中,由资源的close()方法引发的任何异常必须声明为由我的方法引发,或者我必须将整个尝试包装在另一个try中,该语句捕获由close()引发的任何异常

如果是这样,我想知道我是否会充分利用它。我当然不想看到throwclose()引发的异常,调用方不知道该怎么处理。而一个try包装另一个try只是为了处理close()至少在我看来不会很优雅

编辑:我想我不小心问了两个问题,其中一个是重复的

问题1。我必须声明我的方法从close()方法抛出异常,还是在另一次尝试中用资源包装该尝试?(建议的副本中未回答。)

问题2。有没有办法安静地关闭资源?(显然是重复的,所以我把这句话从问题中去掉。希望这能让问题令人满意地独一无二。)


共 (2) 个答案

  1. # 1 楼答案

    引用Java Language Specification ($14.20.3.2)

    14.20.3.2 Extended try-with-resources

    A try-with-resources statement with at least one catch clause and/or a finally clause is called an extended try-with-resources statement. The meaning of an extended try-with-resources statement:

        try ResourceSpecification
            Block
        Catchesopt
        Finallyopt

    is given by the following translation to a basic try-with-resources statement (§14.20.3.1) nested inside a try-catch or try-finally or try-catch-finally statement:

        try {
            try ResourceSpecification
                Block
        }
        Catchesopt
        Finallyopt

    The effect of the translation is to put the ResourceSpecification "inside" the try statement. This allows a catch clause of an extended try-with-resources statement to catch an exception due to the automatic initialization or closing of any resource.

    所以,基本上,包装器已经实现了

  2. # 2 楼答案

    您应该能够简单地添加适当的catch (Exception e) { }子句。如果你需要对一个特定的对象进行特殊处理,或者你可以简单地捕捉Exception,如果你需要的话

    try (Statement stmt = con.createStatement()) {
        ResultSet rs = stmt.executeQuery(query);
    
        while (rs.next()) {
            String coffeeName = rs.getString("COF_NAME");
            int supplierID = rs.getInt("SUP_ID");
            float price = rs.getFloat("PRICE");
    
            System.out.println(coffeeName + ", " + supplierID + ", " + 
                               price + ", " + sales + ", " + total);
        }
    } catch (Exception e) {
        System.out.println("Exception while trying to through the queries. ", e);
    }
    

    因为它是Java 7,所以实际上可以在每个catch子句中放置多个异常,或者只需捕获所需的最外层异常