Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested try catch in PHP

Tags:

People also ask

Can I nest try catch in PHP?

Try-catch blocks in PHP can be nested up to any desired levels and are handled in reverse order of appearance i.e. innermost exceptions are handled first.

What is nested try catch?

The control is then transferred to its parent try block (inner try block 1). If it does not handle the exception, then the control is transferred to the main try block (outer try block) where the appropriate catch block handles the exception. It is termed as nesting.

Is nested try catch good?

Nesting try-catch blocks severely impacts the readability of source code because it makes it to difficult to understand which block will catch which exception.


Consider:

try{
    class MyException extends Exception{}
    try{
        throw new MyException;
    }
    catch(Exception $e){
        echo "1:";
        throw $e;
    }
    catch(MyException $e){
        echo "2:";
        throw $e;
    }
}
catch(Exception $e){
    echo get_class($e);
}

I am confused with this try and catch. I am expecting a 2:MyException result because of the second try throw MyException. But the actual result is 1:MyException. What is the explanation?