当函数或方法包含错误/无效数据时,返回false或抛出异常?考虑一个Loginer类有这样的方法:
public boolean login(String username){
//retrieve data...
if(username.equals(record.username)){
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
然后在主要或其他类
String username = "ggwp";
if(Loginer.login(username)){
//successful login, show homepage...
new User(username);
} else {
//invalid username
}
Run Code Online (Sandbox Code Playgroud)
它不会效率低,因为它已经使用if-else语句两次检查,一次在Loginer中,另一次在main处再次检查为true.不会尝试捕获会做同样的事情吗?让Loginer抛出异常:
public User login(String username){
//retrieve record data...
if(username.equals(record.username)){
return new User(username);
}
/* Exception if no record found for such username */
throw new MyException("invalid username");
}
Run Code Online (Sandbox Code Playgroud)
然后在主要:
String username = "ggwp2";
User theUser;
try{
//sucessful login
theUser = Loginer.login(username);
}catch(MyException e){
//invalid username
}
Run Code Online (Sandbox Code Playgroud)
try-catch不需要第二次检查true或false.(这个例子我使用返回User对象,它可能是void并且只返回,但是为什么使用boolean,最终会被检查两次?)
一些网站消息人士表示不要使用try-catch进行"代码跳转",但在这种情况下它只是做同样的事情.(try-catch与if-else语句太相似) …