Confused by this PHP Exception try..catch nesting

Posted by Domenic on Stack Overflow See other posts from Stack Overflow or by Domenic
Published on 2010-04-06T16:45:11Z Indexed on 2010/04/06 16:53 UTC
Read the original article Hit count: 249

Filed under:
|

Hello. 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.

© Stack Overflow or respective owner

Related posts about php

Related posts about exception-handling