You can catch both exceptions and errors by catching(Throwable)
PHP 7 は大半のエラーがどのようにPHPから報告されるかを変更しています。 PHP 5 で使われていたこれまでのエラー報告メカニズムを使うかわりに、 大半のエラーを Error 例外としてスローするようになったのです。
通常の例外と同様、Error 例外も、 最初にマッチした catch ブロックで現れます。 マッチするブロックがなければ、set_exception_handler() で設定したデフォルトの例外ハンドラが呼ばれます。 デフォルトの例外ハンドラもない場合は、例外が fatal error に変換されて、 これまでのバージョンのエラーと同じように扱われます。
Error クラスは
Exception を継承していないので、
キャッチし損ねた例外を
catch (Exception $e) { ... }
ブロックで受け止めているような PHP 5 のコードでは、
Error をキャッチできません。
catch (Error $e) { ... }
ブロックを用意するか、あるいは
set_exception_handler() でハンドラを設定する必要があります。
You can catch both exceptions and errors by catching(Throwable)
php 7.1
try {
// Code that may throw an Exception or ArithmeticError.
} catch (ArithmeticError | Exception $e) {
// pass
}
Throwable does not work on PHP 5.x.
To catch both exceptions and errors in PHP 5.x and 7, add a catch block for Exception AFTER catching Throwable first.
Once PHP 5.x support is no longer needed, the block catching Exception can be removed.
try
{
// Code that may throw an Exception or Error.
}
catch (Throwable $t)
{
// Executed only in PHP 7, will not match in PHP 5
}
catch (Exception $e)
{
// Executed only in PHP 5, will not be reached in PHP 7
}