Xebozone
Xebozone

Reputation: 510

Java: Does try execute all lines, or jump to catch?

I was wondering about the execution path of a java try-catch statement, and couldn't find details on the following situation.

If I have a statement such as:

try {

  // Make a call that will throw an exception
  thisWillFail();

  // Other calls below:
  willThisExecute();

} catch (Exception exception) {
  // Catch the exception
}

Will the lines below thisWillFail() execute before moving to the catch, or will execution of the try statement jump to the catch as soon as an exception is thrown?

In other words, is it safe to assume that call 'b' following call 'a' will execute, provided call 'a' does not throw an exception in the try statement?

Thanks

Upvotes: 6

Views: 7006

Answers (5)

Leontsev Anton
Leontsev Anton

Reputation: 817

in case of exception try block will execute all statements before exception statement and then control goes to catch block.

Upvotes: -1

MichaelGofron
MichaelGofron

Reputation: 1410

If any clause included in the try clause generates an error, the code in the catch clause (corresponding to that error - you can have multiple catch for a single try) will be executed. There is no way to know in advance if a particular clause will fail or not, only to try to recover after the error happens.

In other words as soon as an exception is thrown by the thisWillFail() function the catch clause will be executed and thereby bypassing the willThisExecute() function.

Upvotes: 4

Yogender Solanki
Yogender Solanki

Reputation: 72

It will not execute any further instruction in the that try block it will jump to the catch block and execute catch block.And after that it will execute finally(remember finally will be executed in every case whether there is any exception or not).To read further here is a good article line([http://tutorials.jenkov.com/java-exception-handling/basic-try-catch-finally.html])

Upvotes: 1

Eran
Eran

Reputation: 393846

NO, the lines below thisWillFail() will not execute. The execution would move to the catch block.

Upvotes: 12

Kon
Kon

Reputation: 10810

Why don't you just test this yourself?

Once an exception is thrown, the try block is abandoned and execution resumes at the catch/finally statements.

Upvotes: 1

Related Questions