HOME HTML EDITOR C JAVA PHP

PHP Exceptions

An exception is an object that describes an error or unexpected behavior of a PHP script. Exceptions are used to change the normal flow of a code execution if a specified error condition occurs.

1. The Basic Try...Catch Syntax

To handle exceptions, we wrap our code in a try block. If an error occurs, the code execution jumps to the catch block.

<?php
  try {
    // Code that may throw an exception
    $result = 5 / 0;
  } catch (Exception $e) {
    // Code that runs if an exception occurs
    echo "Unable to divide by zero.";
  }
?>

2. Throwing an Exception

The throw statement allows a user-defined function or method to throw an exception. When an exception is thrown, the code following it will not be executed.

<?php
  function divide($dividend, $divisor) {
    if($divisor == 0) {
      throw new Exception("Division by zero");
    }
    return $dividend / $divisor;
  }

  try {
    echo divide(5, 0);
  } catch(Exception $e) {
    echo "Error: " . $e->getMessage();
  }
?>

3. The Try...Catch...Finally Block

The finally block can be used after or instead of catch blocks. Code inside the finally block will always run, regardless of whether an exception was thrown or caught.

<?php
  try {
    echo divide(5, 0);
  } catch(Exception $e) {
    echo "Process failed.";
  } finally {
    echo "Cleanup task complete.";
  }
?>

4. The Exception Object

When an exception is caught, you get an Exception Object which contains useful information about the error:

5. Custom Exceptions

You can create your own exception classes by extending the built-in Exception class to handle specific types of errors in your application.

Pro Tip: Use exceptions for "exceptional" circumstances—things that shouldn't happen during normal operation. For regular logic (like checking if a user entered a password), standard if...else statements are usually better.