Custom Errors in PHP

<?php

// A custom error class usually has the suffix "Error".
class ArgError extends Exception {
    private $arg;

    public function __construct($arg, $message) {
        parent::__construct($message);
        $this->arg = $arg;
    }

    public function getArg() {
        return $this->arg;
    }

    public function __toString() {
        return $this->arg . " - " . $this->getMessage();
    }
}

function f($arg) {
    if ($arg == 42) {
        // Return our custom error.
        throw new ArgError($arg, "can't work with it");
    }
    return $arg + 3;
}

function main() {
    try {
        $result = f(42);
    } catch (ArgError $ae) {
        echo $ae->getArg() . "\n";
        echo $ae->getMessage() . "\n";
    } catch (Exception $e) {
        echo "err doesn't match ArgError\n";
    }
}

main();

In PHP, we can implement custom errors by extending the built-in Exception class. This is similar to implementing the error interface in other languages.

The ArgError class is our custom error type. It includes an $arg property and overrides the __toString() method to provide a custom string representation of the error.

The f() function demonstrates how to throw our custom error when a specific condition is met.

In the main() function, we use a try-catch block to handle the custom error. PHP’s exception handling mechanism is used instead of the errors.As() function. We catch the specific ArgError first, and if it doesn’t match, we catch any other Exception.

To run this program, save it as custom_errors.php and execute it with PHP:

$ php custom_errors.php
42
can't work with it

This example demonstrates how to create and use custom error types in PHP, providing more detailed and specific error information in your applications.