如何从 Java 的 try/catch 块中抛出异常的点恢复执行?

How do I resume the execution from the point where the exception was thrown in try/catch block in Java?

我的用例要求我检查 DBConnections 以确保我们有正确的 url。

假设我们有 10 个 Oracle 数据库的列表,并且 DB4 的连接 url 格式错误。我们想捕获 db4 连接失败但仍想检查列表中所有剩余的数据库。

allDBs = {DB1{用户名,url,通过},DB2{用户名,url,通过},....DB10{用户名,url,通过} }


DBList <DbDetails> allDBs = new DBList <DbDetails>();
try{
 for(DbDetails db : allDBs)
 {
            dbUrl = db.getDbUrl();
            dbUsername = db.getUserName();
            dbPassword = db.getPass();
            DbDetails dbDetails = new DbDetails(dbUrl, dbUsername, dbPassword);

            dataSource = dbConfig.setOrclDataSource(dbDetails);
            conn = dataSource.getConnection();
            String selectQuery = "select 1 from dual";
            SqlFunction sf = new SqlFunction(dataSource, selectQuery);
            sf.compile()
   }
}
catch(SQLException se){
 connFailDBList.add(dbDetail);
 LOG.error(se.getMessage());
}

因为 DB4 url 格式不正确。通过以上逻辑,SQLException 在 DB4 处被捕获。但是如何恢复对列表中剩余数据库的检查?

只需交换 for 周期和 try-catch:

DBList <DbDetails> allDBs = new DBList <DbDetails>();
for(DbDetails db : allDBs){
 try{
   //  checking connectivity here
 }catch(SQLException se){
   connFailDBList.add(dbDetail);
   LOG.error(se.getMessage());
 }
}

只需将 try/catch 块移动到 for 循环中。

DBList<DbDetails> allDBs = new DBList<DbDetails>();

    for (DbDetails db : allDBs) {
        try {
            dbUrl = db.getDbUrl();
            dbUsername = db.getUserName();
            dbPassword = db.getPass();
            DbDetails dbDetails = new DbDetails(dbUrl, dbUsername, dbPassword);

            dataSource = dbConfig.setOrclDataSource(dbDetails);
            conn = dataSource.getConnection();
            String selectQuery = "select 1 from dual";
            SqlFunction sf = new SqlFunction(dataSource, selectQuery);
            sf.compile()
        } catch (SQLException se) {
            connFailDBList.add(dbDetail);
            LOG.error(se.getMessage());
        }
                
    }