Java – returns Boolean or try catch

When a function or method contains error / invalid data, return false or throw an exception?

public boolean login(String username){
    //retrieve data...
    if(username.equals(record.username)){
        return true;
    }
    return false;
}

Then in the main or other classes

String username = "ggwp";
if(Loginer.login(username)){
    //successful login,show homepage...
    new User(username);
} else {
    //invalid username
}

It will not be inefficient because it has been checked twice with an if else statement, once in the loginer and once again at main Won't you try to capture and do the same thing? Let the loginer throw an exception:

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");
}

Then in the main:

String username = "ggwp2";
User theUser;
try{
    //sucessful login
    theUser = Loginer.login(username);
}catch(MyException e){
    //invalid username
}

Try catch does not need to check true or false a second time (in this example, I use to return the user object, which may be void and only return, but why is it checked twice when using Boolean?)

Some website sources say don't use try catch for "code jump", but in this case it just does the same thing (try catch and if else statements are too similar)

So which is right and why? If this problem is not correct, please guide and sorry, I am a novice oo

Solution

Short answer:

You should never use try / catch to implement "control logic"

As Andy Turner said, "only exceptions are used to handle exception situations."

This is true for all languages that support exceptions – not just Java Useful articles:

Best practices for exceptions

PS: try / catch is not similar to "if / else" It has different realization, different intention... And its price is more expensive

Additional notes:

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>