0

I have this code:

class MyException extends Exception {}

function __construct($palabra){
echo 'hola.adios';
}

try {
throw new MyException('Oops!');
}catch (Exception $e) {
echo "Caught Exceptionn";
}catch (MyException $e) {
echo "Caught MyExceptionn";
}

when I run it in an explorer, the output is "Caught Exceptionn" instead of "Caught MyExceptionn" although is a new MyException and thouhg I have construct in this class!!

dapaez
  • 1
  • 2

2 Answers2

0

Your first catchblock references Exception, which is the parent class of MyException. This means that if you have catch(Exception) it will also process all MyException AND all Exception classes.

Reverse your order to resolve your problem (ie. making it run from most specific to most generic):

class MyException extends Exception {}

function __construct($palabra){
echo 'hola.adios';
}

try {
throw new MyException('Oops!');
}catch (MyException $e) {
   echo "Caught MyExceptionn";
}catch (Exception $e) {
   echo "Caught Exceptionn";
}
Tularis
  • 1,506
  • 1
  • 8
  • 17
0

You should chain your catch blocks from most specific to least. So basically, it should look like

class MyException extends Exception {}

function __construct($palabra){
    echo 'hola.adios';
}

try {
    throw new MyException('Oops!');
} catch (MyException $e) {
    echo "Caught MyException";
} catch (Exception $e) {
    echo "Caught Exception";
}

If the exception is of type MyException, it would be catched in the first catch block, if it wasn't, it'll be caught in the more general Exception catch block.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308