return boolean or try catch











up vote
3
down vote

favorite
1












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.










share|improve this question




















  • 1




    Use exceptions to handle exceptional conditions only. If you can predict and detect the problem, there is no need to use an exception.
    – Andy Turner
    Nov 10 at 20:52








  • 1




    There is the option of returning Optional<User> which is only filled if valid, empty otherwise.
    – daniu
    Nov 10 at 21:00












  • Any opposition to closing this as a duplicate of stackoverflow.com/questions/2972307/… ?
    – Marco13
    Nov 10 at 21:01















up vote
3
down vote

favorite
1












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.










share|improve this question




















  • 1




    Use exceptions to handle exceptional conditions only. If you can predict and detect the problem, there is no need to use an exception.
    – Andy Turner
    Nov 10 at 20:52








  • 1




    There is the option of returning Optional<User> which is only filled if valid, empty otherwise.
    – daniu
    Nov 10 at 21:00












  • Any opposition to closing this as a duplicate of stackoverflow.com/questions/2972307/… ?
    – Marco13
    Nov 10 at 21:01













up vote
3
down vote

favorite
1









up vote
3
down vote

favorite
1






1





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.










share|improve this question















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.







java oop






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 10 at 20:55

























asked Nov 10 at 20:51









A. Go

164




164








  • 1




    Use exceptions to handle exceptional conditions only. If you can predict and detect the problem, there is no need to use an exception.
    – Andy Turner
    Nov 10 at 20:52








  • 1




    There is the option of returning Optional<User> which is only filled if valid, empty otherwise.
    – daniu
    Nov 10 at 21:00












  • Any opposition to closing this as a duplicate of stackoverflow.com/questions/2972307/… ?
    – Marco13
    Nov 10 at 21:01














  • 1




    Use exceptions to handle exceptional conditions only. If you can predict and detect the problem, there is no need to use an exception.
    – Andy Turner
    Nov 10 at 20:52








  • 1




    There is the option of returning Optional<User> which is only filled if valid, empty otherwise.
    – daniu
    Nov 10 at 21:00












  • Any opposition to closing this as a duplicate of stackoverflow.com/questions/2972307/… ?
    – Marco13
    Nov 10 at 21:01








1




1




Use exceptions to handle exceptional conditions only. If you can predict and detect the problem, there is no need to use an exception.
– Andy Turner
Nov 10 at 20:52






Use exceptions to handle exceptional conditions only. If you can predict and detect the problem, there is no need to use an exception.
– Andy Turner
Nov 10 at 20:52






1




1




There is the option of returning Optional<User> which is only filled if valid, empty otherwise.
– daniu
Nov 10 at 21:00






There is the option of returning Optional<User> which is only filled if valid, empty otherwise.
– daniu
Nov 10 at 21:00














Any opposition to closing this as a duplicate of stackoverflow.com/questions/2972307/… ?
– Marco13
Nov 10 at 21:01




Any opposition to closing this as a duplicate of stackoverflow.com/questions/2972307/… ?
– Marco13
Nov 10 at 21:01












1 Answer
1






active

oldest

votes

















up vote
6
down vote













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.









share|improve this answer























  • The "PS" indicated that this was supposed to be a comment (so I won't downvote, just wait until you delete it ;-) )
    – Marco13
    Nov 10 at 21:02










  • Yeah, it was meant to be a comment. But responses don't completely "delete", so I'll leave it as a response ... and just delete my previous comment instead. BTW - this post has duplicates, including: Best practice for Java exception handling and Exceptions: Why throw early? Why catch late?
    – paulsm4
    Nov 10 at 21:06












  • While far more expensive, once this path warms up it costs about 1 microsecond, whereas boolean is a fraction of this, but might not be a problem.
    – Peter Lawrey
    Nov 10 at 21:06










  • One final comment: although a good case can be made for throwing a "logon exception" error, I'd just use a boolean. The reason is that the caller who invoked the logon needs to know directly whether it succeeded or not, and take the appropriate action. There shouldn't be any need to "bubble" the logon failure to any other part of the code.
    – paulsm4
    Nov 10 at 22:16













Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














 

draft saved


draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53243285%2freturn-boolean-or-try-catch%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
6
down vote













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.









share|improve this answer























  • The "PS" indicated that this was supposed to be a comment (so I won't downvote, just wait until you delete it ;-) )
    – Marco13
    Nov 10 at 21:02










  • Yeah, it was meant to be a comment. But responses don't completely "delete", so I'll leave it as a response ... and just delete my previous comment instead. BTW - this post has duplicates, including: Best practice for Java exception handling and Exceptions: Why throw early? Why catch late?
    – paulsm4
    Nov 10 at 21:06












  • While far more expensive, once this path warms up it costs about 1 microsecond, whereas boolean is a fraction of this, but might not be a problem.
    – Peter Lawrey
    Nov 10 at 21:06










  • One final comment: although a good case can be made for throwing a "logon exception" error, I'd just use a boolean. The reason is that the caller who invoked the logon needs to know directly whether it succeeded or not, and take the appropriate action. There shouldn't be any need to "bubble" the logon failure to any other part of the code.
    – paulsm4
    Nov 10 at 22:16

















up vote
6
down vote













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.









share|improve this answer























  • The "PS" indicated that this was supposed to be a comment (so I won't downvote, just wait until you delete it ;-) )
    – Marco13
    Nov 10 at 21:02










  • Yeah, it was meant to be a comment. But responses don't completely "delete", so I'll leave it as a response ... and just delete my previous comment instead. BTW - this post has duplicates, including: Best practice for Java exception handling and Exceptions: Why throw early? Why catch late?
    – paulsm4
    Nov 10 at 21:06












  • While far more expensive, once this path warms up it costs about 1 microsecond, whereas boolean is a fraction of this, but might not be a problem.
    – Peter Lawrey
    Nov 10 at 21:06










  • One final comment: although a good case can be made for throwing a "logon exception" error, I'd just use a boolean. The reason is that the caller who invoked the logon needs to know directly whether it succeeded or not, and take the appropriate action. There shouldn't be any need to "bubble" the logon failure to any other part of the code.
    – paulsm4
    Nov 10 at 22:16















up vote
6
down vote










up vote
6
down vote









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.









share|improve this answer














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.










share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 10 at 21:12

























answered Nov 10 at 21:01









paulsm4

75.6k898122




75.6k898122












  • The "PS" indicated that this was supposed to be a comment (so I won't downvote, just wait until you delete it ;-) )
    – Marco13
    Nov 10 at 21:02










  • Yeah, it was meant to be a comment. But responses don't completely "delete", so I'll leave it as a response ... and just delete my previous comment instead. BTW - this post has duplicates, including: Best practice for Java exception handling and Exceptions: Why throw early? Why catch late?
    – paulsm4
    Nov 10 at 21:06












  • While far more expensive, once this path warms up it costs about 1 microsecond, whereas boolean is a fraction of this, but might not be a problem.
    – Peter Lawrey
    Nov 10 at 21:06










  • One final comment: although a good case can be made for throwing a "logon exception" error, I'd just use a boolean. The reason is that the caller who invoked the logon needs to know directly whether it succeeded or not, and take the appropriate action. There shouldn't be any need to "bubble" the logon failure to any other part of the code.
    – paulsm4
    Nov 10 at 22:16




















  • The "PS" indicated that this was supposed to be a comment (so I won't downvote, just wait until you delete it ;-) )
    – Marco13
    Nov 10 at 21:02










  • Yeah, it was meant to be a comment. But responses don't completely "delete", so I'll leave it as a response ... and just delete my previous comment instead. BTW - this post has duplicates, including: Best practice for Java exception handling and Exceptions: Why throw early? Why catch late?
    – paulsm4
    Nov 10 at 21:06












  • While far more expensive, once this path warms up it costs about 1 microsecond, whereas boolean is a fraction of this, but might not be a problem.
    – Peter Lawrey
    Nov 10 at 21:06










  • One final comment: although a good case can be made for throwing a "logon exception" error, I'd just use a boolean. The reason is that the caller who invoked the logon needs to know directly whether it succeeded or not, and take the appropriate action. There shouldn't be any need to "bubble" the logon failure to any other part of the code.
    – paulsm4
    Nov 10 at 22:16


















The "PS" indicated that this was supposed to be a comment (so I won't downvote, just wait until you delete it ;-) )
– Marco13
Nov 10 at 21:02




The "PS" indicated that this was supposed to be a comment (so I won't downvote, just wait until you delete it ;-) )
– Marco13
Nov 10 at 21:02












Yeah, it was meant to be a comment. But responses don't completely "delete", so I'll leave it as a response ... and just delete my previous comment instead. BTW - this post has duplicates, including: Best practice for Java exception handling and Exceptions: Why throw early? Why catch late?
– paulsm4
Nov 10 at 21:06






Yeah, it was meant to be a comment. But responses don't completely "delete", so I'll leave it as a response ... and just delete my previous comment instead. BTW - this post has duplicates, including: Best practice for Java exception handling and Exceptions: Why throw early? Why catch late?
– paulsm4
Nov 10 at 21:06














While far more expensive, once this path warms up it costs about 1 microsecond, whereas boolean is a fraction of this, but might not be a problem.
– Peter Lawrey
Nov 10 at 21:06




While far more expensive, once this path warms up it costs about 1 microsecond, whereas boolean is a fraction of this, but might not be a problem.
– Peter Lawrey
Nov 10 at 21:06












One final comment: although a good case can be made for throwing a "logon exception" error, I'd just use a boolean. The reason is that the caller who invoked the logon needs to know directly whether it succeeded or not, and take the appropriate action. There shouldn't be any need to "bubble" the logon failure to any other part of the code.
– paulsm4
Nov 10 at 22:16






One final comment: although a good case can be made for throwing a "logon exception" error, I'd just use a boolean. The reason is that the caller who invoked the logon needs to know directly whether it succeeded or not, and take the appropriate action. There shouldn't be any need to "bubble" the logon failure to any other part of the code.
– paulsm4
Nov 10 at 22:16




















 

draft saved


draft discarded



















































 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53243285%2freturn-boolean-or-try-catch%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Florida Star v. B. J. F.

Error while running script in elastic search , gateway timeout

Adding quotations to stringified JSON object values