Perintah throw
Perintah throw digunakan untuk secara eksplisit melemparkan sebuah exception di PHP.
Perintah ini menerima satu parameter - objek exception, yang harus merupakan instance dari kelas
yang diwarisi dari kelas dasar Exception. Saat perintah ini dipanggil, eksekusi kode saat ini
langsung dihentikan, dan PHP mencoba mencari blok catch yang sesuai untuk menangani exception tersebut.
Sintaks
throw new ExceptionClass(message, code, previous);
Contoh
Contoh sederhana menghasilkan exception:
<?php
$age = -5;
if ($age < 0) {
throw new Exception('Age cannot be negative');
}
?>
Hasil eksekusi kode:
Fatal error: Uncaught Exception: Age cannot be negative
Contoh
Contoh dengan penanganan exception:
<?php
try {
$res = 10 / 0;
if (is_infinite($res)) {
throw new Exception('Division by zero');
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
?>
Hasil eksekusi kode:
'Error: Division by zero'
Contoh
Penggunaan exception kustom:
<?php
class MyCustomException extends Exception {}
try {
throw new MyCustomException('Custom error message');
} catch (MyCustomException $e) {
echo 'Custom error caught: ' . $e->getMessage();
}
?>
Hasil eksekusi kode:
'Custom error caught: Custom error message'