CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    May 1999
    Posts
    3

    Try, Catch & Throw

    Hi!

    I have a problem regarding try, catch and throw statements.....

    After catching all exceptions with a catch(...) statement, I need to determine the type of the exception. Whether it is a CDBException or a CMemoryException or something else. How can I do this? I am trying to implement the following scenario across many functions:


    try
    {
    // Processing code
    }
    catch(...)
    {
    // Do cleanup

    // Rethrow a user defined exception class, for
    // which I need to know the type of the exception
    }




    I can handle individual exceptions but it will result in the duplication of cleanup code.

    looking forward to any suggestions,

    Regards,
    Praveen


  2. #2
    Guest

    Re: Try, Catch & Throw

    If the object being thrown is derived from CException (which it should be) you can use the CObject::IsKindOf() method to find out the type of object. The CException class will require either an IMPLEMENT_DYNAMIC or an IMPLEMENT_SERIAL method, but you can then use the following syntax:

    if (pObj->IsKindOf( RUNTIME_CLASS(MyExceptionClass) ))

    You can also test against CMemoryException, CFileException, and so on...

    Cheers!
    Humble Programmer
    ,,,^..^,,,


  3. #3
    Join Date
    May 1999
    Location
    Antwerp, Belgium
    Posts
    136

    Re: Try, Catch & Throw

    You can use typeid function for this.

    example :
    if ( typeid(*exception) == typeid(CDBException) )
    {
    // this is a CDBException
    }
    else
    {
    // Another exception
    }



    Note that the typeid test only verifies that an object is exactly of a certain class ("is a").
    In order to verify the compatibility ("is kind of"), the dynamic_cast operation must be used.
    This only works on polymorphic classes (at least one virtual member)

    Hope this helps.


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