I can\'t understand exactly how return
works in try
, catch
.
try
and finally
without
Finally block will always execute even if we caught the exception in catch block or even our try block executed as expected.
so when does finally block will be execute with in the flow...
if we have return statement inside the try/catch block then before executing the return statement finally block will be executed (like as for closing the connection or I/O)
function returnType process() {
try {
// some other statements
// before returning someValue, finally block will be executed
return someValue;
} catch(Exception ex) {
// some error logger statements
// before returning someError, finally block will be executed
return someError;
} finally {
// some connection/IO closing statements
// if we have return inside the finally block
// then it will override the return statement of try/catch block
return overrideTryCatchValue;
}
}
but if you have return statement inside the finally statement then it will override the return statement inside the try or catch block.