gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:35:29 24 4
gpt4 key购买 nike

我有这个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 语句。执行此操作的正确方法是什么?

最佳答案

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

关于java - 如何使用 try-catch 异常改进此代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9634215/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com