try-catch in throw's parent block

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

try-catch in throw's parent block

Post 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
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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");
}
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post 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)
Post Reply