Saturday, November 14, 2009

Exception Handling: What is the output of the following code ?

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

class Foo {
 public function something() {
  throw new AnotherException ( );
 }
 public function somethingElse() {
  throw new MyException ( );
 }
}

$a = new Foo ( );

try {
 try {
  $a->something ();
 } catch ( AnotherException $e ) {
  $a->somethingElse ();
 } catch ( MyException $e ) {
  print "Caught Exception";
 }
} catch ( Exception $e ) {
 print "Didn't catch the Exception!";
}

key point to note in here is exception thrown in catch block wont be caught if its not surrounded by try block.

comments to answer.

1 comments:

  1. The above code prints :

    Didn't catch the Exception!

    because, MyException catch block is not surrounded by try block.

    ReplyDelete