Handling exception question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Paul Czubilinski

    Handling exception question

    Hello,

    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?

    Best rgrds,
    Paul

  • Sjoerd

    #2
    Re: Handling exception question


    Paul Czubilinski wrote:[color=blue]
    > class MyException extends Exception {}[/color]

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

    Comment

    • Paul Czubilinski

      #3
      Re: Handling exception question

      > Since MyException extends Exception, MyException _is_ an Exception.[color=blue]
      > Therefore, catch (Exception $e) will catch it.[/color]

      Ok, so how to make a different exceptions nested?

      Comment

      • Dikkie Dik

        #4
        Re: Handling exception question

        > I have code like this:[color=blue]
        >
        > 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?[/color]


        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(SomeExcep tion $e){...}
        catch(SomeOther Exception $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

        Comment

        • Paul Czubilinski

          #5
          Re: Handling exception question

          Thx, Ive got it :)

          Comment

          Working...