Closed2

JavaScript の入れ子になった try...catch の内側で catch を省略した場合の挙動

snakasnaka

try...catch が入れ子になっている状況で、

  • 内側では try...finally で後始末処理の実行を担保したい ... (1)
  • 外側では try...catch で例外を捕捉して処理を行いたい ... (2)
test.js
try {
  try {
    // Exception occured
    nonExistentFunction();
    // Never reach here
    console.log('Success');
  } finally {
    // (1)
    console.log('finally inside')
  }
} catch(e) {
  // (2)
  console.error("catch outside") 
  console.error(e)
}

結果


> "finally inside"
> catch outside
> ReferenceError: nonExistentFunction is not defined

期待通り、内側の finally (1) の実行後、外側の catch (2) が実行された

このスクラップは4ヶ月前にクローズされました