try {
con = openCon();
ps = con.prepareStatement(sql);
setValues(ps, param);
rs = ps.executeQuery();
return ResultSupport.toResult(rs);
} finally {
closeAll(rs, ps, con);
}
这段代码是怎么执行的?
public boolean Login(Master m) {
boolean bool = false;
// 预编译的SQL语句
String sql = "select * from dbo.master where name=? and password=?";
try {
return BaseDao.execute(sql, m.getName(), m.getPassword());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这样为什么就报错了呢?
con = openCon();
ps = con.prepareStatement(sql);
setValues(ps, param);
rs = ps.executeQuery();
return ResultSupport.toResult(rs);
} finally {
closeAll(rs, ps, con);
}
这段代码是怎么执行的?
public boolean Login(Master m) {
boolean bool = false;
// 预编译的SQL语句
String sql = "select * from dbo.master where name=? and password=?";
try {
return BaseDao.execute(sql, m.getName(), m.getPassword());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这样为什么就报错了呢?
boolean bool = false;
// 预编译的SQL语句
String sql = "select * from dbo.master where name=? and password=?";
try {
return BaseDao.execute(sql, m.getName(), m.getPassword());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}这段代码中,方法体中定义了返回类型为boolean,那么你的return <boolean>必须覆盖所有方法结束情况,当然,在catch内,你可以使用throw new e的方法抛出异常,抛出异常语句是一种变异的return方式,代表出现错误,终止方法,所以你必须选择return操作或者throw一个exception来完成终止方法的操作。
那第一段代码,return放在try 里面,它怎么也不报错啊,是先走finally 再走reutrn吗?
这时并不是直接返回程序调用,只是准备好了返回值,然后转去执行finally;执行完finally之后再取出刚刚准备好的返回值,执行返回操作。
你的第二段代码因为方法定义的是布尔型的,你就必须给方法一个布尔型的返回值。
你加了catch用来捕获异常,这时需要对try中的代码执行时出现异常的情况给出一个返回值。
java code:
public class Test { public static void main(String[] args) {
Test test=new Test();
System.out.println("return:"+test.Login());
}
public boolean Login() {
boolean bool = false;
// try {
// return bool;
//
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// return bool;
// }
try {
return bool;
} finally {
bool=true;
System.out.println("finally:"+bool);
} }
}