ErrorException

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

はじめに

エラー例外です。

クラス概要

class ErrorException extends Exception {
/* プロパティ */
protected int $severity = E_ERROR;
/* 継承したプロパティ */
protected string $message = "";
private string $string = "";
protected int $code;
protected string $file = "";
protected int $line;
private array $trace = [];
private ?Throwable $previous = null;
/* メソッド */
public __construct(
    string $message = "",
    int $code = 0,
    int $severity = E_ERROR,
    ?string $filename = null,
    ?int $line = null,
    ?Throwable $previous = null
)
final public getSeverity(): int
/* 継承したメソッド */
final public Exception::getCode(): int
final public Exception::getFile(): string
final public Exception::getLine(): int
final public Exception::getTrace(): array
}

プロパティ

severity

例外の深刻度

例1 set_error_handler() を使用した、エラーメッセージから ErrorException への変換

<?php
set_error_handler(function (int $errno, string $errstr, string $errfile, int $errline) {
    if (!(error_reporting() & $errno)) {
        // このエラーコードが error_reporting に含まれていない場合
        return;
    }
    if ($errno === E_DEPRECATED || $errno === E_USER_DEPRECATED) {
        // 推奨されない警告の場合は、例外をスローしません。
        // 新規または想定外の渓谷がアプリケーションを壊すからです。
        return;
    }
    throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
});

// 壊れたデータをアンシリアライズすると、エラーハンドラによって
// 警告は ErrorException に変換されます。
unserialize('broken data');
?>

上の例の出力は、 たとえば以下のようになります。

Fatal error: Uncaught ErrorException: unserialize(): Error at offset 0 of 11 bytes in test.php:16
Stack trace:
#0 [internal function]: {closure}(2, 'unserialize(): ...', 'test.php', 16)
#1 test.php(16): unserialize('broken data')
#2 {main}
  thrown in test.php on line 16

目次