我在许多方法中都有以下代码
try{ user = userList.get(user_id); }
catch(Exception e) { return "USER_NOT_FOUND"; }
我发现我自己在不同的方法中使用了很多代码,为了删除重复项,我可以尝试创建一个这样的方法:(示例)
.. returnUser(){
try{ return user = userList.get(user_id); }
catch(Exception e) { return "USER_NOT_FOUND"; }
}
但是,如果找不到用户,这只会返回用户或字符串,并且不会退出方法:(不工作)
public static void main(String[] args){
System.out.pring("This will run always");
User a = returnUser();
System.out.pring("this should only run if a user was returned");
System.out.pring("otherwise 'USER_NOT_FOUND' should be returned and end app.");
....
....
return "Succsess";
}
有一个更好的方法吗?您可以从方法中返回一个刹车并返回字符串并结束该方法吗?
代码示例:
public String completeTodo(){
Todo todo; // Instantiate User object
User user; // Instantiate todo object
try{ todo = todoList.get(user_id); } //repeditive in all functions
catch(Exception e) { return "TODO_NOT_FOUND"; }
try{ user = userList.get(user_id); } //repeditive in some functions
catch(Exception e) { return "USER_NOT_FOUND"; }
if(user.getToken() == token){
user.setDef(1);
return user.toString();
}
return "USER_NOT_VALID";
}