Novice Developer
Novice Developer

Reputation: 4759

Try-Catch and how throw work in catch block

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

Upvotes: 4

Views: 2233

Answers (3)

SingleShot
SingleShot

Reputation: 19131

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.

Upvotes: 3

Mircea Grelus
Mircea Grelus

Reputation: 2915

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

Upvotes: 2

Lou Franco
Lou Franco

Reputation: 89232

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

The return false is never reached.

Upvotes: 11

Related Questions