Cara menggunakan php exceptions

Exception merupakan kondisi pengecualian pada program. Exception akan mengubah alur program ke mode normal jika terjadi error. Dengan kata lain, exception mengabaikan error yang terjadi dan mengerjakan proses tertentu saat exception tertangkap.

Untuk menggunakan exception dilakukan dengan perintah try dan catch. Perintah try berisi kode-kode yang berisi pengecualian program dan perintah catch berfungsi menangkap kode kode yang dikirim oleh pengecualian pada try. Proses pengiriman kode exception ini biasa disebut dengan throw (melempar).


Ketika exception terjadi karena dipicu oleh error, status kode program akan aman karena eksekusi program akan dialihkan ke kode program penanganan exception (exception handler). Jadi pada kondisi ini exception handler akan meresume eksekusi dari status kode yang tersimpan lalu menghentikan eksekusi script dan melanjutkannya dengan kode pada lokasi lain didalam program.

Penggunaan dasar Exception

Untuk menggunakan exception secara sederhana kita memakai kombinasi Try, Throw dan Catch. Pada Try berisi kode-kode perintah yang memicu error dan akan dibuat exception programnya. Hasil exception dari Try akan dilempar (Throw) dan kemudian ditangkap (Catch) lalu dibuat obyek untuk menampilkan informasi exception.

Contoh penggunaan Exception Handler Sederhana

<?php  
//buat fungsi yang berisi exception didalamnya
function cekAngka($angka) {
if($angka>5) {
throw new Exception("Angka harus dibawah 5");
}
return true;
}

//Memicu exception dengan perintah Try, contoh: mengecek angka 7
try {
cekAngka(7);
//Jika error terjadi maka exception akan dilemparkan dan perintah dibawah ini tidak akan dieksekusi
echo 'Jika meliha pesan ini berarti angka yang anda masukkan dibawah 5';
}

//menangkap exception yang dilempar oleh Try dengan catch
catch(Exception $e) {
echo 'Pesan Error: ' .$e->getMessage();
}
?>

Kode diatas akan menampilkan pesan error seperti ini :

Pesan Error: Angka harus dibawah 5

Penjelasan Script:

Pada kode diatas terlihat proses memunculkan exception (try), melemparkan (throw) dan menangkap exception (catch) dan menampilkan informasi exception. Program dimulai dengan membuat fungsi cekAngka yang melemparkan exception jika angka yang dimasukkan lebih besar dari 5.

Baca Juga:  Mengenal Operator pada PHP

Selanjutnya exception dipicu dengan perintah try yang menjalankan fungsi cekAngka(7). Exception yang dihasilkan oleh perintah try selanjutnya ditangkap oleh perintah catch yang kemudian menampilkan Pesan Error yang diset oleh perintah throw pada fungsi cekAngka.

PHP has an exception model similar to that of other programming languages. An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch or finally block.

If an exception is thrown and its current function scope has no catch block, the exception will "bubble up" the call stack to the calling function until it finds a matching catch block. All finally blocks it encounters along the way will be executed. If the call stack is unwound all the way to the global scope without encountering a matching catch block, the program will terminate with a fatal error unless a global exception handler has been set.

The thrown object must be an

0.2
First finally.
Caught exception: Division by zero.
Second finally.
Hello World
2 Throwable. Trying to throw an object that is not will result in a PHP Fatal Error.

As of PHP 8.0.0, the throw keyword is an expression and may be used in any expression context. In prior versions it was a statement and was required to be on its own line.

finally

A finally block may also be specified after or instead of catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.

One notable interaction is between the finally block and a throw1 statement. If a throw1 statement is encountered inside either the try or the catch blocks, the finally block will still be executed. Moreover, the throw1 statement is evaluated when encountered, but the result will be returned after the finally block is executed. Additionally, if the finally block also contains a throw1 statement, the value from the finally block is returned.

Global exception handler

If an exception is allowed to bubble up to the global scope, it may be caught by a global exception handler if set. The set_exception_handler() function can set a function that will be called in place of a catch block if no other block is invoked. The effect is essentially the same as if the entire program were wrapped in a try-catch block with that function as the catch.

Notes

Note:

Internal PHP functions mainly use , only modern Object-oriented extensions use exceptions. However, errors can be easily translated to exceptions with ErrorException. This technique only works with non-fatal errors, however.

Apa itu exception pada PHP?

Exception secara bahasa berarti pengecualian. Sedangkan secara istilah di dalam PHP, ia adalah sebuah perubahan alur program dari kondisi normal ke kondisi tertentu (atau pengecualian tertentu) jika terjadi suatu error (exception).

Apa saja yang bisa dilakukan untuk penanganan exception?

Terdapat dua cara untuk menangani Exception yaitu dengan menangkap Exception dan melempar Exception. Lakukan penanganan exception dengan menangkap Exception menggunakan blok try-catch. Berilah penjelasan (apakah program termasuk unchecked exceptions atau checked exceptions) !

Apa itu Try and Catch?

Tujuan dari blok try-catch adalah menangkap dan menangani pengecualian yang dihasilkan oleh kode kerja.

Apa yang anda ketahui tentang exception handling jelaskan dan berikan contohnya?

Exception Handling merupakan mekanisme yang paling diperlukan dalam menangani error yang terjadi pada saat runtime (program berjalan) atau yang lebih dikenal dengan sebutan runtime error. Secara umum, adanya kesalahan / error yang terjadi pada program pada saat runtime dapat menyebabkan program berhenti atau hang.