Exception handling in php with example

Exception handling in PHP is a way to handle errors gracefully and ensure the application doesn’t crash when something goes wrong. It uses try, catch, and optionally finally blocks to manage exceptions.

Here’s how it works:

  1. Throwing an Exception: If an error occurs, you can “throw” an exception using the throw keyword.
  2. Catching an Exception: The try block contains code that may throw an exception. The catch block handles the exception.
  3. Finally Block (Optional): The finally block contains code that will always execute, regardless of whether an exception was thrown or not.

Syntax

try {
    // Code that may throw an exception
} catch (Exception $e) {
    // Code to handle the exception
} finally {
    // Code that always executes (optional)
}

Example 1: Simple Exception Handling

<?php
function divide($a, $b) {
    if ($b == 0) {
        throw new Exception("Division by zero is not allowed.");
    }
    return $a / $b;
}

try {
    echo divide(10, 2); // This will work
    echo divide(10, 0); // This will throw an exception
} catch (Exception $e) {
    echo "Caught exception: " . $e->getMessage();
} finally {
    echo " - End of division operation.";
}
?>

Output:

5 - Caught exception: Division by zero is not allowed. - End of division operation.

Example 2: Using Custom Exceptions

You can create custom exception classes by extending the base Exception class.

<?php
class CustomException extends Exception {}

function checkNumber($number) {
    if ($number > 100) {
        throw new CustomException("The number is too large.");
    }
    return "The number is acceptable.";
}

try {
    echo checkNumber(50); // This will work
    echo checkNumber(150); // This will throw a custom exception
} catch (CustomException $e) {
    echo "Caught custom exception: " . $e->getMessage();
} catch (Exception $e) {
    echo "Caught general exception: " . $e->getMessage();
} finally {
    echo " - Validation complete.";
}
?>

Output:

The number is acceptable. - Caught custom exception: The number is too large. - Validation complete.

Key Points:

  1. throw keyword: Used to signal that an error has occurred.
  2. try block: Code that might throw an exception.
  3. catch block: Code that handles the thrown exception.
  4. finally block: Code that runs regardless of an exception.
  5. Custom Exceptions: Extend the Exception class for specialized error handling.

Exception handling makes PHP code more robust and easier to debug.