Page 1 of 1

try-catch in throw's parent block

Posted: Wed Aug 01, 2007 8:24 am
by anjanesh
Hi

Code: Select all

class cTest
 {
        public function __construct()
         {
         }

        public function foo1()
         {
                self::foo2();
         }

        public function foo2()
         {
                throw new Exception("error...", 456);
         }
 }
 
try
 {
        $o = new cTest();
        $o->foo1();
 }
catch (Exception $e)
 {
        echo $e->getMessage();
 }
foo2() throws an exception which gets passed to foo1().
In this code, foo1() throws exception to the try block - so its fine.

But, is it necessary to have have a try-catch-throw in foo1() too ?

Thanks

Posted: Wed Aug 01, 2007 8:48 am
by Chris Corbyn
No you don't need try/catch in foo1() but people commonly catch the execption anyway and then throw it again. You'll see this sort of thing in Java a lot.

Code: Select all

function foo1() {
  try {
    self::foo2();
  } catch (Exception $e) {
    throw new Exception($e);
  }
}
Either way, if foo1() calls foo2() and foo2() throws an exception, it will bubble back up through foo1() anyway so it would be documented that way:

Code: Select all

/**
 * Does the one thing.
 * @throws Exception
 */
function foo1() {
  self::foo2();
}

/**
 * Does the two thing.
 * @throws Exception
 */
function foo2() {
  throw new Exception("I'm an exception");
}

Posted: Wed Aug 01, 2007 8:49 am
by timvw
If you know how to handle the exception you could write the try/catch in your Foo1 method and handle it there...
If you don't know how to handle the exception, simply let it bubble up.... (And handle it eg: in your code as you did right now)