简体   繁体   中英

how to improve this code with try-catch exceptions

I have this java code which is a part of a managed bean which is used to display data from database into JSF table.

//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;        
}

I want to improve this code and insert try catch statements. What is the proper way to do this?

Why would you want to do that? If any error occurs, the method doesn't really have what to do, so it seems appropriate to throw an exception in those cases.

The only thing I would change is adding a finally method, to close connections:

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();
}

how to improve this code with try-catch exeptions?

You can review your question title, since you are not asking about improvement , but maybe organizing. Based on your code, I changed your method so that it looks cleaner and more organized about catching exceptions.

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; 
}

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

This is pretty basic Java stuff so I recommend picking up a book and learning the basics. Regardless, I typically do something like the following

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM