Handling exception question

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I have code like this:

class MyException extends Exception {}

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

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

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

Best rgrds,

Re: Handling exception question

Paul Czubilinski wrote:
Quoted text here. Click to load it

Since MyException extends Exception, MyException _is_ an Exception.
Therefore, catch (Exception $e) will catch it.

Re: Handling exception question

Quoted text here. Click to load it

Ok, so how to make a different exceptions nested?

Re: Handling exception question

Quoted text here. Click to load 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  

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

Re: Handling exception question

Thx, Ive got it :)

Site Timeline