CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1
  1. #1
    Join Date
    Nov 2002
    Location
    Foggy California
    Posts
    1,245

    The wrong catch statement catches an exception! Why?

    Q: The wrong catch statement catches an exception in the following code! Why?

    Code:
    #include <iostream>
    
    using namespace std;
    
    class A
    {
    };
    
    class B : public A
    {
    };
    
    int main()
    {
        B b;
    
        try
        {
            throw b;
        }
        catch (A& ea)
        {
            cout << "Caught an instance of A" << endl;
        }
        catch (B& eb)
        {
            cout << "Caught an instance of B" << endl;
        }
        return 0;
    }
    A: No, the code works the way it is supposed to. When a thrown class encounters a parent class in an a catch statement, the class will be recast and copied -- you will not be able to recast a caught pointer back to the original type!

    Catching happens on a "first come, first serve" basis. The first catch statement that can match will. In order to get the above code to work as expected, the catch statement for the B class needs to occur before the catch statement for the A class:

    Code:
    #include <iostream>
    
    using namespace std;
    
    class A
    {
    };
    
    class B : public A
    {
    };
    
    int main()
    {
        B b;
    
        try
        {
            throw b;
        }
        catch (B& eb)
        {
            cout << "Caught an instance of B" << endl;
        }
        catch (A& ea)
        {
            cout << "Caught an instance of A" << endl;
        }
        return 0;
    }

    Last edited by Andreas Masur; July 24th, 2005 at 04:39 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured