PHP Exceptions

Exceptions in PHP are a way to handle errors and other exceptional circumstances in a more controlled manner. Instead of using traditional error handling techniques, PHP provides a structured way to throw and catch exceptions.

Throwing Exceptions

<?php
function checkNumber($number) {
    if ($number < 1) {
        throw new Exception("Value must be greater than 0.");
    }
    return true;
}

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

Output:

Caught exception: Value must be greater than 0.

Explanation: This example demonstrates how to throw an exception using the throw keyword. The checkNumber function throws an exception if the input number is less than 1. The exception is caught in the try-catch block, and the error message is displayed.

Custom Exception Classes

<?php
class CustomException extends Exception {}

function doSomething($value) {
    if ($value < 1) {
        throw new CustomException("Custom error: Value must be greater than 0.");
    }
    return true;
}

try {
    doSomething(0);
} catch (CustomException $e) {
    echo 'Caught custom exception: ' . $e->getMessage();
}
?>

Output:

Caught custom exception: Custom error: Value must be greater than 0.

Explanation: This example shows how to create a custom exception class by extending the built-in Exception class. The doSomething function throws a CustomException if the input value is less than 1.

Finally Block

<?php
function testFinally() {
    try {
        throw new Exception("An error occurred.");
    } catch (Exception $e) {
        echo 'Caught exception: ' . $e->getMessage();
    } finally {
        echo ' This will always execute.';
    }
}

testFinally();
?>

Output:

Caught exception: An error occurred. This will always execute.

Explanation: This example demonstrates the use of the finally block, which is executed after the try and catch blocks, regardless of whether an exception was thrown or not. It ensures that certain code runs after the exception handling process.