Kelas Exception
Kelas Exception mewakili kelas asas untuk semua pengecualian dalam PHP.
Ia mengandungi kaedah-kaedah asas untuk bekerja dengan pengecualian: mendapatkan mesej ralat,
kod ralat, fail dan baris di mana pengecualian berlaku, serta susunan panggilan.
Apabila mencipta pengecualian, anda boleh menghantar mesej, kod ralat dan pengecualian sebelumnya.
Sintaks
new Exception(string $message = "", int $code = 0, Throwable $previous = null);
Contoh
Mari cipta dan urus pengecualian mudah:
<?php
try {
throw new Exception('Something went wrong', 100);
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
?>
Keputusan pelaksanaan kod:
'Error: Something went wrong'
Contoh
Mari gunakan kaedah-kaedah utama kelas Exception:
<?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";
}
?>
Keputusan pelaksanaan kod (contoh):
'Message: Test exception
Code: 123
File: /path/to/file.php
Line: 3'
Contoh
Mari dapatkan susunan panggilan semasa pengecualian:
<?php
function test() {
throw new Exception('Stack trace test');
}
try {
test();
} catch (Exception $e) {
print_r($e->getTrace());
}
?>
Keputusan pelaksanaan kod (contoh):
[
[
'file' => '/path/to/file.php',
'line' => 5,
'function' => 'test',
'args' => []
]
]
Lihat Juga
-
kelas
ErrorException,
yang mewakili ralat dalam bentuk pengecualian -
fungsi
set_exception_handler,
yang menetapkan pengendali pengecualian pengguna