tags:

views:

269

answers:

3

I have question about throw. How will the throw work in the following code? Does the catch block return false?

try
{
    //code
}
catch(Exception ex)
{
    throw;
    return false;
}
+9  A: 

No, it rethrows. Somewhere up the call stack needs to catch it.

The return false is never reached.

Lou Franco
wiil it also return false?
Novice Developer
No. There will not be a return value
Adam Robinson
only if the part of the code catching it returns false.
AlbertoPL
No, it doesn't return, it exits the function via an exception -- the control goes inside of a catch block up the call stack.
Lou Franco
is there any way to return false and also throw?
Novice Developer
No - if you leave via an exception, you cannot return ordinarily. The return statement is never reached - it is dead code.
Jonathan Leffler
I guess the question is what would it mean for you to return false and also throw an exception -- if you want the caller to know that something happened, just return false and then the caller can throw if it has to. Or the caller could catch the exception. Or maybe you need a more complex return that has more information in it.
Lou Franco
+1  A: 

There is no return value. throw stops the execution of the method, and the calling block will receive the rethrown exception.

Mircea Grelus
+1  A: 

Throwing and returning false does not make sense. Exceptions are used to indicate when errors occur so there is no reason to also have a boolean flag indicating so at the same time. Let's assume your try/catch is in a BankAccount class. If your client code looks something like this:

boolean success = bankAccount.withdraw(20.00);
if(success == false) System.out.println("An error! Hmmm... Perhaps there were insufficient funds?");
else placeInWallet(20.00);

You could be doing this instead:

try {
   bankAccount.withdraw(20.00);
   placeInWallet(20.00);
}
catch(InsufficientFunds e) {
   System.out.println("An error! There were insufficient funds!");
}

Which is cleaner because there is a clear separation of normal logic from error handling logic.

SingleShot