exception中finally语句块的return问题:如果try或catch语句中有return,
会先执行finally再执行return,但下面的一段程序我编译后提示缺少return语句,请教各位是怎么回事,
我开始以为只有try中有return确实有可能不执行,于是我又在catch中加了一个return,但提示还是一样。代码如下:
public String printAllCustomers() throws SQLException{
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
String s=null;
StringBuffer sb=new StringBuffer();
try{
con=provider.getConnection();
stmt=con.createStatement();
//查询记录
rs= stmt.executeQuery("SELECT ID,NAME,AGE,ADDRESS from CUSTOMERS");
//输出查询结果
while (rs.next()){
long id = rs.getLong(1);
String name = rs.getString(2);
int age = rs.getInt(3);
String address = rs.getString(4);
//返回结果
sb.append("id="+id+",name="+name+",age="+age+",address="+address);
s=sb.toString();
return s;
}
}catch(SQLException e){
return s;
}
finally{
closeResultSet(rs);
closeStatement(stmt);
closeConnection(con);
}
}
------解决方法--------------------------------------------------------
public String printAllCustomers() throws SQLException{ Connection con=null; Statement stmt=null; ResultSet rs=null; String s=null; StringBuffer sb=new StringBuffer(); try{ con=provider.getConnection(); stmt=con.createStatement(); //查询记录 rs= stmt.executeQuery("SELECT ID,NAME,AGE,ADDRESS from CUSTOMERS"); //输出查询结果 while (rs.next()){ //BEGIN---------------------------------------- long id = rs.getLong(1); String name = rs.getString(2); int age = rs.getInt(3); String address = rs.getString(4); //返回结果 sb.append("id="+id+",name="+name+",age="+age+",address="+address); s=sb.toString(); return s; } //END---------------------------------------- }catch(SQLException e){ return s; } finally{ closeResultSet(rs); closeStatement(stmt); closeConnection(con); } }