PHP ยท Chapter 40 of 44

PHP Exceptions

Exceptions provide a structured way to handle errors that occur during script execution, letting you separate error-handling code from normal logic. When something goes wrong, you can throw an exception, which can then be caught and handled gracefully.

PHP uses try, catch, and optionally finally blocks to manage exceptions. Code that might fail is placed in try, error-handling code goes in catch, and finally runs regardless of whether an exception occurred.

Syntax
try {
  // risky code
} catch (Exception $e) {
  // handle error
} finally {
  // always runs
}

Throwing and catching exceptions

throw new Exception("message") raises an exception. A matching catch (Exception $e) block catches it and can access the error message with $e->getMessage().

The finally block

Code inside finally always runs, whether or not an exception was thrown, making it useful for cleanup tasks like closing a file or database connection.

Example 1 (php)
<?php
  function divide($a, $b) {
    if ($b == 0) {
      throw new Exception("Cannot divide by zero");
    }
    return $a / $b;
  }
  try {
    echo divide(10, 0);
  } catch (Exception $e) {
    echo "Error: " . $e->getMessage();
  }
?>
Output
Error: Cannot divide by zero

The exception thrown inside divide() is caught, and its message is displayed instead of crashing the script.

Example 2 (php)
<?php
  try {
    echo "Trying...";
    throw new Exception("Oops");
  } catch (Exception $e) {
    echo " Caught: " . $e->getMessage();
  } finally {
    echo " Done.";
  }
?>
Output
Trying... Caught: Oops Done.

The finally block runs after the catch block regardless of the outcome.

Key points

  • throw raises an exception when something goes wrong.
  • try/catch lets you handle errors without crashing the script.
  • getMessage() retrieves the error message from a caught exception.
  • finally always runs, whether or not an exception occurred.
๐Ÿ’ก Note: Create custom exception classes by extending Exception when you need more specific error types in larger applications.

๐Ÿ“ Quick Quiz

1. Which keyword raises an exception?

2. Which block always runs, regardless of an exception?

3. Which method retrieves an exception's error message?