← Back to Chapters

PHP Exception Handling – Throwing Exceptions

? PHP Exception Handling – Throwing Exceptions

? Quick Overview

In PHP, exceptions provide a structured and maintainable way to handle runtime errors. Using the throw keyword, you can immediately interrupt normal execution and transfer control to a corresponding catch block.

? Key Concepts

  • Exceptions represent abnormal or unexpected runtime conditions
  • throw creates and triggers an exception object
  • try-catch blocks handle exceptions safely
  • Execution stops immediately when an exception is thrown

? Syntax & Theory

The throw statement creates an instance of the Exception class (or a subclass). PHP then looks for the nearest matching catch block. If none is found, the script terminates with a fatal error.

? Code Example

? View Code Example
// Function that throws an exception for negative numbers
<?php
function checkNumber($number) {
    if ($number < 0) {
        throw new Exception("Negative numbers are not allowed: $number");
    }
    echo "Number is: $number<br>";
}

try {
    checkNumber(10);
    checkNumber(-5);
}
catch (Exception $e) {
    echo "Caught exception: " . $e->getMessage();
}
?>

? Live Output / Explanation

The first function call runs normally. The second call throws an exception, immediately stopping execution inside try and transferring control to catch, where the error message is displayed.

? Interactive Understanding

Imagine exceptions as emergency exits in your program. Once triggered, PHP jumps directly to the error-handling logic instead of continuing blindly. This keeps applications stable and predictable.

Try the Simulation:
Enter a number and click run.

? Use Cases

  • Validating user input
  • Database connection failures
  • File handling errors
  • Business rule enforcement

? Tips & Best Practices

  • Throw exceptions only for truly exceptional conditions
  • Use meaningful exception messages
  • Create custom exception classes when needed
  • Keep error handling centralized and clean

? Try It Yourself

  • Throw different exceptions for zero, negative, and large numbers
  • Create a custom exception class
  • Log exception messages to a file