Contents
try-catch-finallyの挙動を調べてみる
try-catch-finallyのcatchの中でreturnや例外発生をさせた場合の挙動を調べてみます。
対象言語はJavaScript、PHPです。
JavaScript
JavaScriptでcatchの中でreturnした場合
↓調査した際のプログラム↓
1 2 3 4 5 6 7 8 9 10 11 12 |
function test() { try { throw 'error' }catch(e){ console.log('catch'); return 'catch return'; }finally{ console.log('finally'); return 'finally return'; } } console.log(test()); |
↓出力結果↓
1 2 3 |
catch finally finally return |
catchのあとにfinallyが実行されていることが分かる
→catch内のreturn文は動作していない。
JavaScriptでcatchの中で例外発生した場合
↓調査した際のプログラム↓
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
unction test() { try { try { throw 'error' }catch(e){ console.log('catch'); throw 'catch error' }finally{ console.log('finally'); } }catch(e){ return 'catch error2' } } console.log(test()); |
↓出力結果↓
1 2 3 |
catch finally catch error2 |
catchのあとにfinallyが実行されていることが分かる。同時にcatchに投げ、例外も発生している。
PHP
PHPでcatchの中でreturnした場合
↓調査した際のプログラム↓
1 2 3 4 5 6 7 8 9 10 |
<?php try { throw new Exception('error'); } catch(Exception $error) { print "catch\n"; return; } finally { print "finally\n"; return; } |
↓出力結果↓
1 2 |
catch finally |
catchのあとにfinallyが実行されていることが分かる
→JavaScript同様、catch内のreturn文は動作していない。
PHPでcatchの中で例外発生した場合
↓調査した際のプログラム↓
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?php try { try { throw new Exception('error'); } catch(Exception $error) { print "catch\n"; throw $error; } finally { print "finally\n"; } } catch(Exception $error) { print "catch2\n"; } |
↓出力結果↓
1 2 3 |
catch finally catch2 |
JavaScriptと同様にcatchのあとにfinallyが実行されていることが分かる。同時にcatchに投げ、例外も発生している。