「JavaScript」try catch構文で例外処理を実行する

2021年10月12日

書式

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
try {
処理コード
} catch(e){
 例外処理実行
} finally{
 例外があってもなくても実行コード
}
try { 処理コード } catch(e){  例外処理実行 } finally{  例外があってもなくても実行コード }
try {
  処理コード
} catch(e){
 例外処理実行
} finally{
  例外があってもなくても実行コード
}

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<script>
try {
let res = n + 6;
} catch (e) {
// n is not defined
alert(e.message);
} finally {
alert("finally messae");
}
</script>
<script> try { let res = n + 6; } catch (e) { // n is not defined alert(e.message); } finally { alert("finally messae"); } </script>
<script>
  try {
    let res = n + 6;
  } catch (e) {
  // n is not defined
    alert(e.message); 
  } finally {
    alert("finally messae"); 
  }
</script>

結果
n is not defined
finally messae

JavaScript

Posted by arkgame