PHP7のThrowableを利用したキャッチ
PHP7からErrorクラスが新設されて、文法エラーのような例外も捕捉できるようになった。
Errorクラスも既存のExceptionクラスも、Throwableインターフェースを実装しているので、完全なキャッチは以下のようになる、と思う。
<?php function add(int $a, int $b): int { return $a + $b; } echo add(123, 234), "\n"; // => 357 //try { // echo add('hoge', 'fuga'), "\n"; //} //catch (Exception $e) { // echo "Exception: ", $e->getMessage(), "\n"; //} // // 拾えずに「PHP Fatal error: Uncaught TypeError: Argument 1 passed to add() must be of the type integer, string given〜」が発生する try { echo add('hoge', 'fuga'), "\n"; } catch (\Exception $e) { echo "Exception: ", $e->getMessage(), "\n"; } catch (\Throwable $e) { echo "Throwable: ", $e->getMessage(), "\n"; } // 「Throwable: Argument 1 passed to add() must be of the type integer, string given〜」で拾える echo "finish\n"; // この処理も継続して動く