Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return boolean or try catch

Tags:

java

oop

when a function or method encouter error/invalid data, do return false or throw an exception? Consider a class Loginer has such method :

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

then at the main or some other class

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

won't it be inefficient as it has been checked two time with if-else statement, one in Loginer, and another one check for true again at main. won't try catch will do the same? having the Loginer to 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 on the main:

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

the try-catch need no check second time for true or false. (this example i use return User object, it could be void and return nothing but the point is, why use boolean which will eventual being check twice?)

some website sources say not to use try-catch for 'code jumping' but in this case it just do the same. (try-catch is just too similar to if-else statement)

So which is correct and why? please guide and sorry if this question is incorrect, im newbie to OO.

like image 512
A. Go Avatar asked Dec 23 '22 03:12

A. Go


1 Answers

Short answer:

You should NEVER use try/catch for "control logic".

As Andy Turner said, "Use exceptions to handle exceptional conditions only."

This is equally true of all languages that support exceptions - not just Java. Useful article:

Best practices for exceptions

PS: try/catch is NOT "just similar" to "if/else". It has a different implementation, a different intent ... and it's FAR more expensive.

ADDITIONAL NOTE:

Exceptions: Why throw early? Why catch late?

https://softwareengineering.stackexchange.com/questions/231057/exceptions-why-throw-early-why-catch-late

In my experience, its best to throw exceptions at the point where the errors occur. You do this because it's the point where you know the most about why the exception was triggered.

As the exception unwinds back up the layers, catching and rethrowing is a good way to add additional context to the exception. This can mean throwing a different type of exception, but include the original exception when you do this.

Eventually the exception will reach a layer where you are able to make decisions on code flow (e.g a prompt the user for action). This is the point where you should finally handle the exception and continue normal execution.

With practice and experience with your code base it becomes quite easy to judge when to add additional context to errors, and where it's most sensible to actually, finally handle the errors.

  • Catch → Rethrow

    Do this where you can usefully add more information that would save a developer having to work through all the layers to understand the problem.

  • Catch → Handle

    Do this where you can make final decisions on what is an appropriate, but different execution flow through the software.

  • Catch → Error Return

    Whilst there are situations where this is appropriate, catching exceptions and returning an error value to the caller should be considered for refactoring into a Catch → Rethrow implementation.

like image 145
paulsm4 Avatar answered Jan 09 '23 21:01

paulsm4