0
0
PhpHow-ToBeginner · 3 min read

How to Create Custom Exception in PHP: Simple Guide

In PHP, you create a custom exception by defining a new class that extends the built-in Exception class. This lets you throw and catch your own error types using throw and try-catch blocks.
📐

Syntax

To create a custom exception, define a class that extends Exception. You can add your own properties or methods if needed.

  • class YourException extends Exception {}: Defines the custom exception class.
  • throw new YourException('message');: Throws the custom exception.
  • try { ... } catch (YourException $e) { ... }: Catches the custom exception.
php
class MyCustomException extends Exception {
    // You can add custom properties or methods here
}

// Throwing the exception
throw new MyCustomException('Something went wrong');
💻

Example

This example shows how to create a custom exception class, throw it, and catch it to handle errors gracefully.

php
<?php
class MyCustomException extends Exception {
    public function errorMessage() {
        // Custom error message
        return "Error on line " . $this->getLine() . " in " . $this->getFile() . ": <strong>" . $this->getMessage() . "</strong>";
    }
}

try {
    // Simulate an error
    throw new MyCustomException('Custom exception triggered');
} catch (MyCustomException $e) {
    echo $e->errorMessage();
}
?>
Output
Error on line 9 in /path/to/script.php: <strong>Custom exception triggered</strong>
⚠️

Common Pitfalls

Common mistakes when creating custom exceptions include:

  • Not extending the Exception class, which means your class won't behave like an exception.
  • Forgetting to use throw to raise the exception.
  • Not catching the custom exception, causing the script to stop unexpectedly.

Always extend Exception and use try-catch blocks to handle your custom exceptions.

php
<?php
// Wrong: Not extending Exception
class WrongException {
}

// Right: Extending Exception
class RightException extends Exception {
}

try {
    throw new RightException('This is correct');
} catch (RightException $e) {
    echo $e->getMessage();
}
?>
Output
This is correct
📊

Quick Reference

ConceptDescription
class MyException extends ExceptionDefines a custom exception class
throw new MyException('msg')Throws the custom exception
try { ... } catch (MyException $e) { ... }Catches and handles the custom exception
$e->getMessage()Gets the exception message
$e->getCode()Gets the exception code (optional)

Key Takeaways

Create a custom exception by extending the built-in Exception class.
Use throw to raise your custom exception and try-catch to handle it.
Add custom methods to your exception class for clearer error messages.
Always catch your custom exceptions to prevent unexpected script termination.
Remember to extend Exception; otherwise, your class won't work as an exception.