Exception Sınıfı
Exception sınıfı, PHP'deki tüm istisnalar için temel sınıfı temsil eder.
İstisnalarla çalışmak için temel metodları içerir: hata mesajını alma,
hata kodunu, istisnanın oluştuğu dosya ve satırı alma ve ayrıca çağrı yığınını.
Bir istisna oluştururken mesaj, hata kodu ve önceki istisna aktarılabilir.
Sözdizimi
new Exception(string $message = "", int $code = 0, Throwable $previous = null);
Örnek
Basit bir istisna oluşturalım ve işleyelim:
<?php
try {
throw new Exception('Something went wrong', 100);
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
?>
Kodun çalıştırılma sonucu:
'Error: Something went wrong'
Örnek
Exception sınıfının temel metodlarını kullanalım:
<?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";
}
?>
Kodun çalıştırılma sonucu (örnek):
'Message: Test exception
Code: 123
File: /path/to/file.php
Line: 3'
Örnek
Bir istisna sırasında çağrı yığınını alalım:
<?php
function test() {
throw new Exception('Stack trace test');
}
try {
test();
} catch (Exception $e) {
print_r($e->getTrace());
}
?>
Kodun çalıştırılma sonucu (örnek):
[
[
'file' => '/path/to/file.php',
'line' => 5,
'function' => 'test',
'args' => []
]
]
Ayrıca Bakınız
-
ErrorExceptionsınıfı,
hataları istisna olarak temsil eder -
set_exception_handlerişlevi,
özel bir istisna işleyici belirler