PHP Exceptions

PHP Exceptions are a way to handle errors and unexpected situations that occur during the execution of a PHP script. Here are some examples of how to use PHP’s exception handling functionality:

  1. Throwing an exception:
function divide($a, $b) {
    if ($b == 0) {
        throw new Exception('Cannot divide by zero.');
    }
    return $a / $b;
}
try {
    echo divide(10, 0);
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

In this example, a divide() function is defined to divide two numbers, but throws an exception if the second number is zero. The try block is used to call the divide() function, and the catch block is used to handle any exceptions that are thrown.

  1. Defining custom exceptions:
class InvalidInputException extends Exception {
    public function __construct($message, $code = 0, Exception $previous = null) {
        parent::__construct($message, $code, $previous);
    }
}
function validate_input($input) {
    if (!is_numeric($input)) {
        throw new InvalidInputException('Invalid input: ' . $input);
    }
}
try {
    validate_input('abc');
} catch (InvalidInputException $e) {
    echo 'Error: ' . $e->getMessage();
}

In this example, a custom exception class called InvalidInputException is defined to handle errors related to invalid input data. The validate_input() function is defined to check if a value is numeric, and throws an InvalidInputException if it is not. The try block is used to call the validate_input() function, and the catch block is used to handle any InvalidInputException exceptions that are thrown.

Exceptions can be used for a variety of purposes, such as handling errors, validating input data, and debugging code. By using exceptions, developers can create more robust and reliable PHP applications that gracefully handle errors and unexpected situations.