Kelas ErrorException

Kelas ErrorException diwarisi daripada kelas asas Exception dan digunakan untuk menukar ralat PHP kepada pengecualian. Ia menambah maklumat tentang keparahan ralat (severity) kepada fungsi piawai pengecualian. Kelas ini amat berguna apabila digunakan dengan fungsi set_error_handler.

Sintaks

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

Contoh

Mencipta dan mengendalikan ErrorException:

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

Hasil pelaksanaan kod:

php'Error: Critical error Severity: 1'

Contoh

Menukar ralat piawai PHP kepada pengecualian:

php<?php
  function errorHandler($severity, $message, $file, $line) {
    throw new ErrorException($message, 0, $severity, $file, $line);
  }
  
  set_error_handler('errorHandler');
  
  try {
    strpos(); // Bilangan argumen yang tidak betul
  } catch (ErrorException $e) {
    echo 'Caught exception: ' . $e->getMessage();
    echo ' in ' . $e->getFile();
    echo ' on line ' . $e->getLine();
  }
?>

Hasil pelaksanaan kod (contoh):

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

Contoh

Mendapatkan maklumat tentang keparahan ralat:

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');
  }
?>

Hasil pelaksanaan kod:

php'Severity level: 2 Is warning: yes'

Lihat juga

  • kelas Exception,
    kelas asas untuk semua pengecualian dalam PHP
  • fungsi set_error_handler,
    yang menetapkan pengendali ralat pengguna