Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what happen to return statement in catch block

Tags:

javascript

I have tried this code in javascript

function abc(){   try{      console.log(0);      throw "is empty";}   catch(err){      console.log(1);      return true;   }   finally{return false;}   return(4); } console.log(abc());  

I got output as false. I understand Finally always execute regardless of result of try catch but what happen to return statement in catch .

like image 627
Roli Agrawal Avatar asked Jun 27 '16 09:06

Roli Agrawal


People also ask

Can we put return statement in catch block?

Yes, we can write a return statement of the method in catch and finally block.

What happens if we place return statement in try catch block?

Upon the completion of finally block execution, control goes back to the return statement in the try block and returns “returning from try block”. If finally block has a return statement, then the return statements from try/catch blocks will be overridden.

What does return in catch block do?

In a try-catch-finally block that has return statements, only the value from the finally block will be returned. When returning reference types, be aware of any updates being done on them in the finally block that could end up in unwanted results.

Where do return statements go on try catch?

4.4. 1 Write return statement inside try-block & at the end of method; that is just before end of method.


1 Answers

I understand Finally always execute regardless of result of try catch but what happen to return statement in catch .

Return statement in catch will be executed only if the catch block is reached, i.e. if there is an error thrown.

For example

function example() {      try {          throw new Error()         return 1;     }      catch(e) {         return 2;     }     finally {      }  }  

example() will return 2 since an error was thrown before return 1.

But if there is a finally block and this finally block has a return statement then this return will override catch return statement.

For example

function example() {      try {          throw new Error()         return 1;     }      catch(e) {         return 2;     }     finally {          return 3;     }  }  

Now example() will return 3.

In your example, there is a return statement after the finally block. That statement will never get executed.

Try

function example() {      try {          throw new Error()         return 1;     }      catch(e) {         return 2;     }     finally {          return 3;     }     console.log(5)    return 4; }  

It only outputs 3. 5 is never printed since after finally block value is returned.

like image 65
gurvinder372 Avatar answered Sep 22 '22 03:09

gurvinder372