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
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.
in case of exception try block will execute all statements before exception statement and then control goes to catch block.
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.
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.
NO, the lines below thisWillFail()
will not execute. The execution would move to the catch block.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With