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.
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With