PHP catch exception


Answers ( 1 )


    In PHP, exceptions are used for error handling in a more elegant and manageable way compared to traditional error-handling techniques.

    To catch an exception in PHP, you typically use a try-catch block. Here's a basic example:

    try {
        // Code that may throw an exception
        // For example, opening a file, or executing a database query
    } catch (Exception $e) {
        // Code to handle the exception
        // $e is the exception object that holds details about the error
        echo 'Caught exception: ',  $e->getMessage(), "\n";

    In this structure:

    • The try block contains the code that might throw an exception.
    • The catch block is used to handle the exception. It catches any exception that occurs in the corresponding try block.
    • $e is the exception object, and it contains information about the exception, such as the error message ($e->getMessage()).

    PHP also allows for multiple catch blocks to handle different types of exceptions, and a finally block that is executed regardless of whether an exception was caught or not.

    Here's a more detailed example, including different exception types:

    try {
        // Code that may throw different types of exceptions
    } catch (InvalidArgumentException $e) {
        // Handle InvalidArgumentException specifically
        echo 'Invalid argument: ', $e->getMessage(), "\n";
    } catch (Exception $e) {
        // Handle any other exceptions
        echo 'Caught exception: ', $e->getMessage(), "\n";
    } finally {
        // Code that runs regardless of whether an exception was caught
        echo "Finally block executed.\n";

    In this example:

    • Different types of exceptions can be caught and handled separately.
    • The finally block is optional and used for code that should execute regardless of the outcome of the try-catch blocks.

    PHP has a built-in Exception class, but you can also create custom exception classes by extending the Exception class. This allows for more granular control over exception handling.

Leave an answer