PHP ZCE mock test, interview preparation, daily lessons under chalk talk

Thursday, January 12, 2012

ZCE Zend Certified Engineer Nested Try Catch Problem Solution

View the Complete Blog on ZCE


class MyException extends Exception { }
class Test {
        public function testing()
        {
                try
                {
                        try
                        {
                                throw new MyException('foo!');
                        }
                        catch (Exception $e)
                        {
                                echo 'cought1';
                                /* rethrow it */
                                throw $e;
                        }
                        catch (MyException $e)
                        {
                                echo 'cought2';
                                /* rethrow it */
                                throw $e;
                        }
                }
                catch (MyException $e)
                {
                        echo 'cought3';
                        echo $e->getMessage();
                }
        }
}

$foo = new Test;
$foo->testing();

Answer: cought1cought3foo!
Thrown exception will be first caught by 'caught1' because Exception class that is the generic Handler for all sort of exceptions. Now as it rethrows the exception, it will be caught by Outer Catch Block.

No comments:

Post a Comment