Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

try catch finally #202

Open
teazean opened this issue Mar 1, 2018 · 2 comments
Open

try catch finally #202

teazean opened this issue Mar 1, 2018 · 2 comments

Comments

@teazean
Copy link
Owner

teazean commented Mar 1, 2018

文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#The_finally_block

The finally block contains statements to execute after the try and catch blocks execute but before the statements following the try...catch statement.

总结就是:『finally中的代码』总会执行,无视 try/catch 里面的任何 throw error&return,『finally中的代码』执行时机是先于任何『next/outer的语句』。

@teazean
Copy link
Owner Author

teazean commented Mar 1, 2018

throw error demo

try {
  try {
    throw new Error('oops');
  }
  finally {
    console.log('finally');
  }
}
catch (ex) {
  console.error('outer', ex.message);
}

// Output:
// "finally"
// "outer" "oops"

@teazean
Copy link
Owner Author

teazean commented Mar 1, 2018

return demo

function f() {
  try {
    console.log(0);
    throw 'bogus';
  } catch(e) {
    console.log(1);
    return true; // this return statement is suspended
                 // until finally block has completed
    console.log(2); // not reachable
  } finally {
    console.log(3);
    return false; // overwrites the previous "return"
    console.log(4); // not reachable
  }
  // "return false" is executed now  
  console.log(5); // not reachable
}
f(); // console 0, 1, 3; returns false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant