编写异常的规范

错误的编码:

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值