スクリプト全体が停止しないようにするための「例外処理」を設定するための命令文。
'use strict';
//try{...}catch(e){...}finally{...}命令のみのシンプルな使用例
var i = 2;
try{
i = i * j;//jは定義していないので例外(エラー)が発生し、chatchへ進む。
}catch(e){//エラー内容がErrorオブジェクト(e)に引き渡され、messageプロパティで表示している。
document.getElementById('hoge1').textContent='catch = ' + e.message;
}finally{//例外の有無にかかわらず、最終的に実行される。finallyは、不要の場合は省略してもよい。
document.getElementById('hoge2').textContent='finally';
};
//throw命令を使用した例
var k = 4;
try{
if(k>3){//throw命令は、if文など条件分岐と一緒に利用するケースが多い。
throw new Error('error message of throw');//条件にあったら例外を発生させてErrorオブジェクトをcathcへ渡す。
}
}catch(e){
document.getElementById('hoge3').textContent=e.message;
};
//関数とともに使用した例
function fuga1(value){
if(arguments.length !== 1){//関数の引数の数をarguments.lengthで確認し比較。
throw new Error('arguments error');//関数の引数が1つ以上だったのでthrowを発動。
}
}
try{
fuga1('fugafuga','fugafugafuga');
}catch(e){
document.getElementById('hoge4').textContent=e.message;
};
<p data-height=”300″ data-theme-id=”12804″ data-slug-hash=”OpMGxY” data-default-tab=”result” data-user=”nwst” data-embed-version=”2″ data-pen-title=”OpMGxY” class=”codepen”>See the Pen <a href=”https://codepen.io/nwst/pen/OpMGxY/”>OpMGxY</a> by nwstcode (<a href=”https://codepen.io/nwst”>@nwst</a>) on <a href=”https://codepen.io”>CodePen</a>.</p>
<script async src=”https://production-assets.codepen.io/assets/embed/ei.js”></script>