Alex Rivera | Logout

Confused by this PHP Exception try..catch nesting

Asked 2010-04-06T16:45:11.120
16

I'm confused by the following code:

class MyException extends Exception {}
class AnotherException extends MyException {}

class Foo {
  public function something() {
    print "throwing AnotherException\n";
    throw new AnotherException();
  }
  public function somethingElse() {
    print "throwing MyException\n";
    throw new MyException();
  }
}

$a = new Foo();

try {
  try {
    $a->something();    

  } catch(AnotherException $e) {
    print "caught AnotherException\n";
    $a->somethingElse();    
  } catch(MyException $e) {
    print "caught MyException\n";
  }
} catch(Exception $e) {
  print "caught Exception\n";
}

I would expect this to output:

throwing AnotherException
caught AnotherException
throwing MyException
caught MyException

But instead it outputs:

throwing AnotherException
caught AnotherException
throwing MyException
caught Exception

Could anyone explain why it "skips over" catch(MyException $e) ?

Thanks.

Edit
Report

1 Answer

7

Only because there isn't enough room for this in a comment. Think of the try...catch as an if...else loop. You wouldn't expect the following:

$a = 10;
if($a == 9)
    print "\$a == 9";
elseif($a == 10) {
    $a = 11;
    echo "now \$a == 11";
} elseif($a == 11) {
    echo "\$a == 11";
}

to print out the last condition ("\$a == 11"), because the condition was already met by the first elseif. The same is true with the try...catch. If the condition is met, it doesn't continue searching for new conditions in the same scope.

answered 2010-04-06T17:20:07.633

Your Answer