HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Exception Handling

Exceptions are used to change the normal flow of a script when a specified error condition occurs. Unlike regular errors, exceptions are **objects** that contain information about the failure, including the message, file path, and line number.


1. The Concept of "Throwing"

When an error occurs, you "throw" an exception. This stops the current function's execution and looks for code that can "catch" the error.

<?php
    function checkNumber($number) {
        if($number > 1) {
            // Signals that an exception has occurred
            throw new Exception("Value must be 1 or below");
        }
        return true;
    }
?>

2. The Exception Object

Inside an exception, PHP stores several useful pieces of information. The most common methods are:

Method Description
getMessage() Returns the message passed to the constructor.
getCode() Returns the error code (if any).
getFile() Returns the full path of the file where the error happened.
getLine() Returns the line number of the error.
Why use Exceptions? They separate the "Error Signaling" from the "Error Handling." You can throw an error deep inside your app and decide how to handle it at the very top level (like showing a specific UI component).
Uncaught Exceptions: If you throw an exception but never catch it, PHP will trigger a **Fatal Error** with the message "Uncaught Exception." This will stop your script completely.
Pro Tip: You can create your own custom classes that extend Exception to handle specific types of errors (like DatabaseException or AuthException).

Key Takeaways

  • Exceptions are **objects**, not just strings.
  • Use the throw keyword to signal an error.
  • Exceptions provide stack trace info (file, line, parent calls).
  • Always aim to **catch** exceptions to prevent script crashes.
  • They are the standard for error handling in Object-Oriented PHP.