Re: Handling exception question



I have code like this:

class MyException extends Exception {}

function x() {
try {
throw new MyException()
} catch (Exception $e) {
echo 'Exception catched';
exit;
}

try {
x();
} catch (MyException $e) {
echo 'MyException catched';
exit;
}



I cannot understand why this code catches Exception instead of
MyException? Can you please tell me what is wrong with it?


There's nothing wrong with it. In function x you throw an exception (a MyException to be exact) and catch it again, because you catch any exception. So the function x does not throw an exception to the outside world. If you want to catch specific exceptions, state them in the catch part:

Try{...}
catch(SomeException $e){...}
catch(SomeOtherException $se){...}

So you can use more than one catch. If you want to handle all exceptions, but some specifically, state the specific ones first, and the more generic ones below them.

Best regards
.


Quantcast