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

phpthrow new ExceptionClass(message, code, previous);

Contoh

Contoh sederhana menghasilkan exception:

php<?php
  $age = -5;
  if ($age < 0) {
    throw new Exception('Age cannot be negative');
  }
?>

Hasil eksekusi kode:

phpFatal error: Uncaught Exception: Age cannot be negative

Contoh

Contoh dengan penanganan exception:

php<?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:

php'Error: Division by zero'

Contoh

Penggunaan exception kustom:

php<?php
  class MyCustomException extends Exception {}
  
  try {
    throw new MyCustomException('Custom error message');
  } catch (MyCustomException $e) {
    echo 'Custom error caught: ' . $e->getMessage();
  }
?>

Hasil eksekusi kode:

php'Custom error caught: Custom error message'

Lihat juga

  • konstruksi try,
    yang mendefinisikan blok kode untuk menangani exception
  • konstruksi catch,
    yang menangkap dan menangani exception
  • kelas Exception,
    yang merupakan kelas dasar untuk semua exception