try ... catch による例外処理
JavaScript では例外処理を行うための手段として、try-catch-finally をサポートしています。
try に続くブロックで処理を行い、そこで何らかの例外的状況に遭遇した場合、catch ブロックに制御が移ります。
catch ではその例外に関連付いたオブジェクトを受け取ることもできます。
catch から抜けたときに finally ブロックがあれば、finally が実行されます。
もし catch ブロックが存在しないで、finally しかないときには、当然ながら catch ブロックは実行されず finally ブロックが実行されます。
それではさっそく、 試してみましょう。
try {
document.write('Entering try...<br>');
foo();
document.write('Exit try<br>');
}
catch(e){
document.write('Entering catch...<br>');
document.write('typeof(e) = ' + typeof(e) + '<br>' );
for(var prop in e){
document.write('e[' + prop + '] = '+e[prop]+'<br>');
}
document.write('Exit catch<br>');
}
finally {
document.write('Entering finally...<br>');
document.write('Exit finally.');
}
このコードで問題なのは、foo() の行です。foo はどこでも定義されていないので、関数呼び出しのように見えますが、失敗します。
これをマイクロソフトの Internet Explorer で実行した場合、次のようになりました。
Entering try... Entering catch... typeof(e) = object e[message] = The value of the property 'foo' is null or undefined, not a Function object e[description] = The value of the property 'foo' is null or undefined, not a Function object e[number] = -2146823281 e[name] = TypeError Exit catch Entering finally... Exit finally.
Firefox では次のようになりました。
Entering try... Entering catch... typeof(e) = object e[message] = foo is not defined e[fileName] = http://localhost/keicode-javascript/bar.js e[lineNumber] = 3 e[stack] = @http://localhost/keicode-javascript/bar.js:3 e[name] = ReferenceError Exit catch Entering finally... Exit finally.
いずれにせよ、foo という未定義の変数に対して関数のように呼び出したことによって、 catch ブロックへ制御が移り、その後、finally が実行されたことが分かりますね。