错误的编码:
OutputStreamWriter out = new OutputStreamWriter();
Connection conn = DriverManager.getConnection(url,user,pwd);
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery( "select uid, name from user");
while (rs.next()) {
out.println("ID" + rs.getString("uid") " ,姓名:" + " + rs.getString("name"));
}
rs.close();
stmt.close();
conn.close();
out.close();
}
catch(Exception ex) {
ex.printStackTrace();
}
原因:
丢弃异常 (15~27行)
不指定具体的异常 (15行)
占用资源不释放 (3行~13行)
不说明异常的详细信息(3行~17行)
过于庞大的try块(3行~13行)
编写原则:
既然捕获了异常,就要对它进行适当的处理。不要捕获异常之后又把它丢弃,不予理睬
在catch语句中尽可能指定具体的异常类型,必要时使用多个catch。不要试图处理所有可能出现的异常
保证所有资源都被正确释放。充分运用finally关键词
在异常处理模块中提供适量的错误原因信息,组织错误信息使其易于理解和阅读
尽量减小try块的体积
全面考虑可能出现的异常以及这些异常对执行流程的影响
修改后的代码:
OutputStreamWriter out = new OutputStreamWriter();
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = DriverManager.getConnection(url,user,pwd);
stmt = conn.createStatement();
rs = stmt.executeQuery("select uid, name from user");
while (rs.next())
{
out.println(" ID " + rs.getString(" uid ") + " ,姓名: " + rs.getString("name"));
}
} catch (SQLException sqlex) {
out.println("警告:数据不完整!");
throw new ApplicationException("读取数据时出现SQL错误!", sqlex);
} catch (IOException ioex) {
throw new ApplicationException("写入数据时IO错误", ioex);
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException sqlex2) {
System.err.println("不能关闭数据集: " + sqlex2.toString());
}
}
if (stmt != null) {
try {
stmt.close();
} catch(SQLException ioex2) {
System.err.println("不能关闭statement:" + ioex2.toString());
}
}
if (conn != null) {
try {
conn.close();
} catch(SQLException sqlex2) {
System.err.println("不能关闭数据库连接: " + sqlex2.toString());
}
}
if (out != null) {
try {
out.close();
} catch(IOException ioex2){
System.err.println("不能关闭输出文件:" + ioex2.toString());
}
}
}