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
new Exception(string $message = "", int $code = 0, Throwable $previous = null);
Näide
Loome ja töötleme lihtsa erandi:
<?php
try {
throw new Exception('Midagi läks valesti', 100);
} catch (Exception $e) {
echo 'Viga: ' . $e->getMessage();
}
?>
Koodi täitmise tulemus:
'Viga: Midagi läks valesti'
Näide
Kasutame klassi Exception põhimeetodeid:
<?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):
'Sõnum: Test erand
Kood: 123
Fail: /path/to/file.php
Rida: 3'
Näide
Saame väljakutsete virna erandi korral:
<?php
function test() {
throw new Exception('Stack trace test');
}
try {
test();
} catch (Exception $e) {
print_r($e->getTrace());
}
?>
Koodi täitmise tulemus (näide):
[
[
'file' => '/path/to/file.php',
'line' => 5,
'function' => 'test',
'args' => []
]
]
Vaata ka
-
klass
ErrorException,
mis esindab vigu eranditena -
funktsioon
set_exception_handler,
mis seab kasutaja määratud erandite töötleja