LoginSignup
2
3

More than 5 years have passed since last update.

throwより後ろのコードへは到達しない

Posted at

結論

  • throwされるとcatchへ飛ぶ
  • Uncaughtおよびthrowするオブジェクトが不正な場合は、Fatal errorになる
  • よって、throwより後のコードへは到達しない。

見かけたコード

メソッド内の記述
try {
    // hogehoge
} catch (Exception $e) {
    throw new Exception(/* hugahuga */);
    return;
}

静的解析でもunreachableと出ていたのだが、不安になったので念のため。

どんなケースが考えられるか

throwしたのに次の行へ行く…
ざっと考えてみて、やはりエラー関係で起きそうかなと思ったので列挙してみる。

  • 例外がcatchされない
  • 不正な値がthrowされる
  • 上記のエラーから意図的に復帰する

列挙と言ってもこの位しか思いつかない。

では、試す。

検証コード


<?php

// http://ngyuki.hatenablog.com/entry/2013/12/24/182034 お借りしました
set_error_handler(function ($errno, $errstr, $errfile, $errline) {
    echo "Error[$errno]: $errstr\n";
});


try {

    // 複数throwを書いているのは便宜上
    throw new aException; // PHP Fatal error:  Class 'aException' not found
    throw new StdClass;  // PHP Fatal error:  Exceptions must be valid objects derived from the Exception base class
    throw null;          // PHP Fatal error:  Can only throw objects
    throw new Exception; // PHP Fatal error:  Uncaught exception 'Exception'

    echo 'reach!';

} catch (RuntimeException $e){
}

以上、E_RECOVERABLE_ERRORでもないFatal errorでした。
なので復帰も不可。

ちなみに、
PHP: set_exception_handler - Manual

PHP: set_error_handler - Manual
と異なり、次の命令に継続されることはありません。
一度、set_exception_handler内でtrigger_errorしてset_error_handlerで継続させるというよくわからないこともしてみましたが、継続先は当然set_error_handler内になり意味は無いです。

おまけ

<?php

set_error_handler(function ($errno, $errstr, $errfile, $errline) {
    echo "Error[$errno]: $errstr\n";
});

try {
    throw new Exception;
    hell:
    echo "Welcome to ようこそ 地ャパリパーク";
} catch (Exception $e){
   goto hell;
}
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3