Klass Exception
Klassen Exception utgör basklassen för alla undantag i PHP.
Den innehåller grundläggande metoder för att arbeta med undantag: att få felmeddelandet,
felkoden, filen och radnumret där undantaget uppstod, samt anropsstacken.
När man skapar ett undantag kan man skicka med ett meddelande, en felkod och ett tidigare undantag.
Syntax
new Exception(string $message = "", int $code = 0, Throwable $previous = null);
Exempel
Låt oss skapa och hantera ett enkelt undantag:
<?php
try {
throw new Exception('Något gick fel', 100);
} catch (Exception $e) {
echo 'Fel: ' . $e->getMessage();
}
?>
Resultat av kodkörning:
'Fel: Något gick fel'
Exempel
Låt oss använda huvudmetoderna i klassen Exception:
<?php
try {
throw new Exception('Testundantag', 123);
} catch (Exception $e) {
echo 'Meddelande: ' . $e->getMessage() . "\n";
echo 'Kod: ' . $e->getCode() . "\n";
echo 'Fil: ' . $e->getFile() . "\n";
echo 'Rad: ' . $e->getLine() . "\n";
}
?>
Resultat av kodkörning (exempel):
'Meddelande: Testundantag
Kod: 123
Fil: /sökväg/till/fil.php
Rad: 3'
Exempel
Låt oss få anropsstacken vid ett undantag:
<?php
function test() {
throw new Exception('Stackspårningstest');
}
try {
test();
} catch (Exception $e) {
print_r($e->getTrace());
}
?>
Resultat av kodkörning (exempel):
[
[
'file' => '/sökväg/till/fil.php',
'line' => 5,
'function' => 'test',
'args' => []
]
]
Se även
-
klassen
ErrorException,
som representerar fel som undantag -
funktionen
set_exception_handler,
som sätter en användardefinierad undantagshanterare