rexhin rexhin - 5 months ago 11
PHP Question

PHP unable to caught exception thrown inside catch

I have extended

Exception
class two times to caught different types of exceptions. When first exception is caught I check for another error and if there is an error I throw a new exception again.
The problem is that I can not caught the second exception.

class FIRST extends Exception {}
class SECOND extends Exception {}

try {
throw new FIRST("FIRST", 1);
} catch(FIRST $e) {
//caught

if(sth) {
echo 'ok'; //printed
throw new SECOND("SECOND", 1);
echo 'ok'; //never printed
}
}

catch(SECOND $e) {
//not caught
}

catch(PDOException $e) {
//caught
}

finally {
//
}

Answer

The catch blocks only catch exceptions coming from the try block.

If you need to catch exceptions thrown from any of the catch blocks you have to wrap the inner code in another try-catch structure:

try {
    throw new FIRST("FIRST", 1);
} catch(FIRST $e) {
    //caught

    try {
        if(sth) {
            echo 'ok'; //printed
            throw new SECOND("SECOND", 1);
            echo 'ok'; //never printed
        }
    } catch (SECOND $e) {
        //caught
    }
}

catch(SECOND $e) {
    //not caught
}

catch(PDOException $e) {
    //caught
}

finally {
    //
}