Jeffrey Cordero Jeffrey Cordero - 4 months ago 16
PHP Question

PHP check thrown exception type

Of course in PHP you can catch all thrown exceptions with:

try{
/* code with exceptions */
}catch(Exception $e) {
/* Handling exceptions */
}


But is there a way to check the exception type of the thrown exception from inside the catch block?

Answer

You can have multiple catch blocks to catch different Exception types. See below:

try {
    /* code with exceptions */
} catch (MyFirstCustomException $e) {
    // We know it is a MyFirstCustomException
} catch (MySecondCustomException $e) {
    // We know it is a MyFirstSecondException
} catch (Exception $e) {
    // If it is neither of the above, we can catch all remaining exceptions.
}

You can also use the get_class method to get the full class name of any object, including Exceptions.

Comments