ErrorExceptionクラス

ErrorExceptionクラスは、基底クラスExceptionを継承し、PHPエラーを例外に変換するために使用されます。 これは、標準の例外機能にエラーの深刻度(severity)情報を追加します。このクラスは、 set_error_handler関数と共に使用する場合に特に便利です。

構文

phpnew ErrorException(
  string $message = "",
  int $code = 0,
  int $severity = E_ERROR,
  string $filename = __FILE__,
  int $lineno = __LINE__,
  Throwable $previous = null
);

例

ErrorExceptionを作成して処理します:

php<?php
  try {
    throw new ErrorException('Critical error', 0, E_ERROR);
  } catch (ErrorException $e) {
    echo 'Error: ' . $e->getMessage();
    echo ' Severity: ' . $e->getSeverity();
  }
?>

コード実行結果:

php'Error: Critical error Severity: 1'

例

標準のPHPエラーを例外に変換します:

php<?php
  function errorHandler($severity, $message, $file, $line) {
    throw new ErrorException($message, 0, $severity, $file, $line);
  }
  
  set_error_handler('errorHandler');
  
  try {
    strpos(); // 引数の数が不正
  } catch (ErrorException $e) {
    echo 'Caught exception: ' . $e->getMessage();
    echo ' in ' . $e->getFile();
    echo ' on line ' . $e->getLine();
  }
?>

コード実行結果 (例):

php'Caught exception: strpos() expects at least 2 parameters, 0 given in /path/to/file.php on line 10'

例

エラーの深刻度に関する情報を取得します:

php<?php
  try {
    throw new ErrorException('Warning message', 0, E_WARNING);
  } catch (ErrorException $e) {
    echo 'Severity level: ' . $e->getSeverity();
    echo ' Is warning: ' . ($e->getSeverity() === E_WARNING ? 'yes' : 'no');
  }
?>

コード実行結果:

php'Severity level: 2 Is warning: yes'

関連項目

  • クラス Exception,
    PHPにおけるすべての例外の基底クラス
  • 関数 set_error_handler,
    ユーザー定義のエラーハンドラを設定します