有 Java 编程相关的问题?

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

java如何使用trycatch异常改进此代码

我有这个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) 个答案

  1. # 1 楼答案

    how to improve this code with 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. # 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();
    }
    
  3. # 3 楼答案

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

  4. # 4 楼答案

    这是非常基本的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
        }
    }