Klass Exception

Klass Exception on kõigi PHP erandite põhiklass. See sisaldab põhimeetodeid eranditega töötamiseks: veateate saamine, veakoodi, faili ja rea saamine, kus erand tekkis, ning väljakutsete virna. Erandi loomisel saab edastada sõnumi, veakoodi ja eelneva erandi.

Süntaks

phpnew Exception(string $message = "", int $code = 0, Throwable $previous = null);

Näide

Loome ja töötleme lihtsa erandi:

php<?php
  try {
    throw new Exception('Midagi läks valesti', 100);
  } catch (Exception $e) {
    echo 'Viga: ' . $e->getMessage();
  }
?>

Koodi täitmise tulemus:

php'Viga: Midagi läks valesti'

Näide

Kasutame klassi Exception põhimeetodeid:

php<?php
  try {
    throw new Exception('Test erand', 123);
  } catch (Exception $e) {
    echo 'Sõnum: ' . $e->getMessage() . "\n";
    echo 'Kood: ' . $e->getCode() . "\n";
    echo 'Fail: ' . $e->getFile() . "\n";
    echo 'Rida: ' . $e->getLine() . "\n";
  }
?>

Koodi täitmise tulemus (näide):

php'Sõnum: Test erand
Kood: 123
Fail: /path/to/file.php
Rida: 3'

Näide

Saame väljakutsete virna erandi korral:

php<?php
  function test() {
    throw new Exception('Stack trace test');
  }
  
  try {
    test();
  } catch (Exception $e) {
    print_r($e->getTrace());
  }
?>

Koodi täitmise tulemus (näide):

php[
  [
    'file' => '/path/to/file.php',
    'line' => 5,
    'function' => 'test',
    'args' => []
  ]
]

Vaata ka