需要帮助理解内部 try catch 和外部 try catch

Ric*_*hie 2 java

我收到了另一位开发人员从我这里传递的一些代码。它有一个数据库调用,该调用有一个不带 catch 的内部 try 块,然后是一个带 catch 的外部 try 块。

我需要一些帮助来理解它的含义。因为内部 try 块上没有捕获,这是否意味着数据库层中的任何异常都将被忽略?是否有外部 try catch 块仅捕获 getConnection 和 closeStatement 的错误?

感谢您对此的帮助。

public int doKeywordSearch (
    String username,
    String sessionId,
    String[] keywords, 
    String status) throws RetekServiceException {

    int totalRecords = 0;
    Connection connection = null;
    CallableStatement callStmt = null;
    try {
        connection = DaoUtils.getDataSource().getConnection();      
        try {   
            callStmt = connection.prepareCall(DaoConstants.ITEM_SEARCH_KEYWORD_SQL);
            callStmt.setString(1, username);                                                    // p_vUsername
            callStmt.setString(2, sessionId);                                                   // p_vSid
            callStmt.setString(3, StringUtils.clean(keywords.length > 0 ? keywords[0] : null)); // p_vKeyword1 
            callStmt.setString(4, StringUtils.clean(keywords.length > 1 ? keywords[1] : null)); // p_vKeyword2
            callStmt.setString(5, StringUtils.clean(keywords.length > 2 ? keywords[2] : null)); // p_vKeyword3 
            callStmt.setString(6, StringUtils.clean(keywords.length > 3 ? keywords[3] : null)); // p_vKeyword4
            callStmt.setString(7, StringUtils.clean(keywords.length > 4 ? keywords[4] : null)); // p_vKeyword5
            callStmt.setString(8, status);                                                      // p_vStatus
            callStmt.registerOutParameter(9, OracleTypes.INTEGER);              
            callStmt.execute();
            totalRecords = callStmt.getInt(9);
            connection.commit();
        }
        finally {
            DaoUtils.closeStatement(callStmt);
        }
    }
    catch(SQLException e) {
        DaoUtils.doRollback(connection, e);
    }
    catch(NamingException e) {          
        throw new RetekServiceException("Could not do keyword search.", e);
    }
    finally {
        DaoUtils.closeConnection(connection);
    }                   
    return totalRecords;
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*zyk 5

Atry{} catch(){} finally {}不需要同时catchfinally,只需要其中之一。它是如何工作的,当其中一个catch块处理的异常被抛出到该块内时,就会调用try该块。catch否则,异常会像往常一样向上传播(它到底在哪里传播,我将在一分钟内解释)。无论是否发生异常,finally 块几乎都会被调用(请检查 Java 规范,以了解可能会跳过 finally 块的极少数情况)

如果在内部 try块中发生异常并且没有catch可以处理它的子句,则外部块 try/catch将尝试使用外部块catch的适当子句来处理它,否则如果外部块中不存在这样的子句,则异常将向上传播(到调用此方法的方法或一直到 JVM)。 try/catchcatch try/catch

实际上上面的例子没有多大意义,你也可以将语句放在外部的finally块中......

另外,正如其他人指出的,如果您使用的是 java7 并且您可以使用它connection,它将自动处理资源关闭,并且您不必再手动编写。 AutoCloseabletry-with-resourcesfinally