Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 613
Xebozone Avatar asked Jun 28 '14 14:06

Xebozone


People also ask

What happens in try catch Java?

Java try and catch The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

Are all the statements in the try block executed?

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

Does execution continue after try catch?

It always executes, regardless of whether an exception was thrown or caught. You can nest one or more try statements. If an inner try statement does not have a catch -block, the enclosing try statement's catch -block is used instead.

Which statement is true about the try () block?

A try statement executes a block. If a value is thrown and the try statement has one or more catch clauses that can catch it, then control will be transferred to the first such catch clause. If that catch block completes normally, then the try statement completes normally.


Video Answer


2 Answers

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

like image 72
Eran Avatar answered Oct 01 '22 20:10

Eran


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.

like image 29
MichaelGofron Avatar answered Oct 01 '22 20:10

MichaelGofron