iidear / blog

blog
0 stars 0 forks source link

陷阱 #17

Open iidear opened 4 years ago

iidear commented 4 years ago

try {} catch {} finally

finally 一定会执行,且 finally 中的 return 优先于 try、catch 中的 return .

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/try...catch https://stackoverflow.com/questions/3837994/why-does-a-return-in-finally-override-try

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

// 注: 此 try catch 语句需要在 function 中运行才能作为函数的返回值, 否则直接运行会报语法错误
// Output:
// "inner" "oops"
// "finally"