0
0
PhpHow-ToBeginner · 3 min read

How to Throw Exception in PHP: Syntax and Examples

In PHP, you throw an exception using the throw keyword followed by a new Exception object. This interrupts normal code flow and passes control to the nearest try-catch block that handles the exception.
📐

Syntax

To throw an exception in PHP, use the throw keyword followed by a new instance of the Exception class or any class that extends Exception. This signals an error or unexpected condition.

  • throw: keyword to raise the exception
  • new Exception(): creates the exception object with an optional message
php
throw new Exception("Error message here");
💻

Example

This example shows how to throw an exception inside a function and catch it using a try-catch block. The catch block handles the error gracefully by printing the exception message.

php
<?php
function checkNumber($number) {
    if ($number > 1) {
        throw new Exception("Number must be 1 or less.");
    }
    return true;
}

try {
    checkNumber(5);
    echo "Number is valid.";
} catch (Exception $e) {
    echo "Caught exception: " . $e->getMessage();
}
?>
Output
Caught exception: Number must be 1 or less.
⚠️

Common Pitfalls

Common mistakes when throwing exceptions in PHP include:

  • Throwing exceptions without a try-catch block, which causes the script to stop abruptly.
  • Using throw with something that is not an Exception object.
  • Not providing a meaningful message in the exception, making debugging harder.

Always ensure exceptions are caught or the script will terminate with a fatal error.

php
<?php
// Wrong: throwing a string instead of Exception object
// throw "Error occurred"; // This causes a fatal error

// Right: throwing an Exception object
throw new Exception("Proper error message");
📊

Quick Reference

Keyword/FunctionPurpose
throwRaises an exception
new Exception(message)Creates an exception object with a message
tryDefines a block to test code that may throw exceptions
catch (Exception $e)Handles the exception thrown in try block
getMessage()Retrieves the exception message

Key Takeaways

Use throw new Exception("message") to raise an exception in PHP.
Always catch exceptions with try-catch blocks to handle errors gracefully.
Throw only objects that extend the Exception class.
Provide clear messages in exceptions to help with debugging.
Uncaught exceptions will stop script execution with a fatal error.