PHP

Keyword catch PHP

Definisi dan Penggunaan

Kata kunci catch digunakan untuk menangani pengecualian yang dilemparkan oleh kode di blok percobaan sebelumnya.

Contoh
Catch Exception:

<?php
try {
  throw new Exception("Ini pengecualian");
} catch(Exception $e) {
  echo $e->getMessage();
}
?>
  // Output : Ini pengecualian
  

Contoh Lain

Contoh
Gunakan tangkapan untuk berbagai jenis pengecualian:

<?php
try {
  $rand = rand(0, 2);
  switch($rand) {
    case 0: throw new Exception();
    case 1: throw new OutOfBoundsException();
    case 2: throw new LogicException();
}

} catch(OutOfBoundsException $e) {
  echo "Caught an out of bounds exception";
} catch(LogicException $e) {
  echo "Caught a logic exception";
} catch(Exception $e) {
  echo "Caught an ordinary exception";
}
?>
  // Output : Caught an out of bounds exception

Hanifah Nurbaeti