Exception Klassi
Exception klassi PHPdagi barcha istisnolar uchun asosiy klassni ifodalaydi.
U istisnolar bilan ishlash uchun asosiy metodlarni o'z ichiga oladi: xato xabari,
xato kodi, istisno yuzaga kelgan fayl va qatorni olish, shuningdek chaqiruvlar stekini olish.
Istisno yaratishda xabar, xato kodi va oldingi istisnoni uzatish mumkin.
Sintaksis
new Exception(string $message = "", int $code = 0, Throwable $previous = null);
Misol
Oddiy istisno yaratamiz va uni qayta ishlaymiz:
<?php
try {
throw new Exception('Something went wrong', 100);
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
?>
Kodni bajarish natijasi:
'Error: Something went wrong'
Misol
Exception klassining asosiy metodlaridan foydalanamiz:
<?php
try {
throw new Exception('Test exception', 123);
} catch (Exception $e) {
echo 'Message: ' . $e->getMessage() . "\n";
echo 'Code: ' . $e->getCode() . "\n";
echo 'File: ' . $e->getFile() . "\n";
echo 'Line: ' . $e->getLine() . "\n";
}
?>
Kodni bajarish natijasi (misol):
'Message: Test exception
Code: 123
File: /path/to/file.php
Line: 3'
Misol
Istisno paytida chaqiruvlar stekini olamiz:
<?php
function test() {
throw new Exception('Stack trace test');
}
try {
test();
} catch (Exception $e) {
print_r($e->getTrace());
}
?>
Kodni bajarish natijasi (misol):
[
[
'file' => '/path/to/file.php',
'line' => 5,
'function' => 'test',
'args' => []
]
]
Shuningdek qarang
-
ErrorExceptionklassi,
bu xatolarni istisnolar shaklida ifodalaydi -
set_exception_handlerfunksiyasi,
bu foydalanuvchi istisnolar qayta ishlovchisini o'rnatadi