Confused by this PHP Exception try..catch nesting
- by Domenic
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.