你碰到的问题有可能是这样出现的:
public Strint getName(){
String name=null;
...
...
if(a condition){
return name;//尽管有return语句,但是放在一个有可能进入的代码范围里头,有可能造成无返回值
}
}这种情况还有可能出现于try...catch里头,如:public String getName(){
String name=null;
try{
...
...
return name;//当异常出现时,无返回值
} catch(Exception x){
}
}解决这个问题的办法,有很多,呵呵,自己试试看.
public Strint getName(){
String name=null;
...
...
if(a condition){
return name;//尽管有return语句,但是放在一个有可能进入的代码范围里头,有可能造成无返回值
}
}这种情况还有可能出现于try...catch里头,如:public String getName(){
String name=null;
try{
...
...
return name;//当异常出现时,无返回值
} catch(Exception x){
}
}解决这个问题的办法,有很多,呵呵,自己试试看.
public double getTotal(){
double total=0;
......
try{
......
if (condition){
......
return total;
}catch(Exception e){
.....
}
我把return total;放到try catch块外面编译就没问题了。可是
另一个方法public Collection getAll(){}
和上面类似却没问题。
这是什么原因呢?
逻辑上有可能是这个方法结束的地方都应该有return才比较稳妥
public double ejbHomeGetTotalBankValue() {
PrepareStatement pstmt+null;
Connection conn=null;
try{
conn=getConnection();
pstmt=conn.prepareStatement("select sum(balance) as total from accounts");
ResultSet rs+pstmt.executequery();
if (rs.next()){
return rs.getDouble("total");
}catch(Exception e){
......
}finally{
......
}public Collection ejbFindByOwnerName(String name) throws FinderException {
PreparedStatement pstmt=null;
Connection conn=null;
Vector v =new Vector();
try{
conn=getConnection();
pstmt=conn.prepareStatement("select id from accounts where ownername=?");
pstmt.setString(1,name);
ResultSet rs=pstmt.executeQuery();
while(rs.next()){
String id =rs.getString("id");
v.addElement(new AccountPK(id));
}
return v;
}catch......
解决一: ejbHomeGetTotalBankValue throws DatabaseException(自定义的exception)
解决二:
public double ejbHomeGetTotalBankValue() {
PrepareStatement pstmt+null;
Connection conn=null;
double total=0.0;
try{
conn=getConnection();
pstmt=conn.prepareStatement("select sum(balance) as total from accounts");
ResultSet rs+pstmt.executequery();
if (rs.next()){
total= rs.getDouble("total");
}catch(Exception e){
......
}finally{
return total;
}
但是这样处理会有含糊的地方,比如,有可能accounts里头无记录,因而返回0,也可能是因为中途数据库异常,返回0值.那么上一级调用者就无法知道具体原因,因而不是好的处理方式,建议使用第一种.2.ejbFindByOwnerName(String name)
在finally中返回vector.