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;
}
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;
}
No, it rethrows. Somewhere up the call stack needs to catch it.
The return false
is never reached.
There is no return value. throw
stops the execution of the method, and the calling block will receive the rethrown exception.
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.