如何使用try-catch异常改进此代码

时间:2012-03-09 12:42:10

标签: java jdbc try-catch

我有这个java代码,它是托管bean的一部分,用于将数据从数据库显示到JSF表中。

//connect to DB and get customer list
public List<Dashboard> getDashboardList() throws SQLException {

    if (ds == null) {
        throw new SQLException("Can't get data source");
    }

    //get database connection
    Connection con = ds.getConnection();

    if (con == null) {
        throw new SQLException("Can't get database connection");
    }

    PreparedStatement ps = con.prepareStatement(
            "SELECT * from GLOBALSETTINGS");

    //get customer data from database
    ResultSet result = ps.executeQuery();

    List<Dashboard> list = new ArrayList<Dashboard>();

    while (result.next()) {
        Dashboard cust = new Dashboard();

        cust.setUser(result.getString("SessionTTL"));
        cust.setPassword(result.getString("MAXACTIVEUSERS"));


        //store all data into a List
        list.add(cust);
    }
    ps.close();
    con.close();
    return list;        
}

我想改进此代码并插入try catch语句。这样做的正确方法是什么?

4 个答案:

答案 0 :(得分:2)

你为什么要那样做?如果发生任何错误,该方法实际上没有做什么,所以在这些情况下抛出异常似乎是合适的。

我唯一要改变的是添加一个finally方法来关闭连接:

try {
    PreparedStatement ps = con.prepareStatement(
            "SELECT * from GLOBALSETTINGS");

    //get customer data from database
    ResultSet result = ps.executeQuery();

    List<Dashboard> list = new ArrayList<Dashboard>();

    while (result.next()) {
        Dashboard cust = new Dashboard();

        cust.setUser(result.getString("SessionTTL"));
        cust.setPassword(result.getString("MAXACTIVEUSERS"));


        //store all data into a List
        list.add(cust);
    }
}
finally {
    ps.close();
    con.close();
}

答案 1 :(得分:2)

  

如何使用try-catch exeptions改进此代码?

您可以查看问题标题,因为您不是在询问改进,但可能正在组织。根据您的代码,我更改了您的方法,使其看起来更干净更有组织地捕捉异常。

public List<Dashboard> getDashboardList(DataSource ds)
{   
    List<Dashboard> list = new ArrayList<Dashboard>();
    Connection con = null;
    PreparedStatement ps = null;
    try
    {
        con = ds.getConnection();
        ps = con.prepareStatement("SELECT * from GLOBALSETTINGS");
        //get customer data from database
        ResultSet result = ps.executeQuery();
        while (result.next())
        {
            Dashboard cust = new Dashboard();
            cust.setUser(result.getString("SessionTTL"));
            cust.setPassword(result.getString("MAXACTIVEUSERS"));
            list.add(cust);
        }
    }
    catch(Exception e1)
    {
        // Log the exception.
    }
    finally
    {
        try
        {
             if(ps != null)
                  ps.close();
             if(con != null)
                  con.close();
        }
        catch(Exception e2)
        {
            // Log the exception.
        }
    }
    return list; 
}

答案 2 :(得分:1)

不确定您的意思是正确的,但是如果从方法中删除顶部throws SQLException,您的IDE将显示任何未捕获异常的工具提示,并且您可以自动插入每个缺少的异常方式。

答案 3 :(得分:1)

这是非常基本的Java内容,因此我建议您阅读一本书并学习基础知识。无论如何,我通常会做类似以下的事情

Connection conn = null;
try {
  // DB code
} catch (SQLException se) {
  log.error("Experienced SQLException in method foo", se);
  FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Oops!  You messed up!", null);
  FacesContext.getCurrentInstance().addMessage(null, msg);
} finally {
  if (conn != null && conn.isOpen()) {
    try {
      conn.close();
    } catch (SQLException see) {
      log.error("Connection can't be closed!");
      // Faces message or something like it
    }
}