Link to home
Start Free TrialLog in
Avatar of jmnolan
jmnolan

asked on

try-catch block and unhandled exception

I have an MFC app with the following code:

  CDatabase* cdbDatabase = new CDatabase;
  cdbDatabase->OpenEx("DSN=OracleTest;UID=scott;PWD=tiger;");
  cout << cdbDatabase->IsOpen() << endl;
  CRecordset* rs = new CRecordset(cdbDatabase);

  try
  {
    rs->Open(CRecordset::snapshot, "SELECT USER FROM DUAL;");
  }
  catch (CException e)
  {
    cout << "Caught exception" << endl;
  }
  catch (...)
  {
    cout << "Caught in ellipses" << endl;
  }

When run it outputs:
1
Caught in ellipses

If I take out the catch(...) statement I get a Microsoft Visual C++ error: Unhandled exception in db_test.exe (KERNEL32.DLL): 0xE06D7363: Microsoft C++ Exception.

What is causing this exception? It gets trapped in the catch(...) block but what do I do with it there? How do I access the error message?
ASKER CERTIFIED SOLUTION
Avatar of SDU
SDU

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The reason it flows to catch (...) is because the CRecordset::Open function throws either CDBException * or CMemoryException *. The correct way to handle it is

try
{
    rs->Open(CRecordset::snapshot, "SELECT USER FROM DUAL;");
}
catch (CDBException *pe)
{
    pe->Delete();
}
catch (CMemoryException *pe)
{
    pe->Delete();
}


or


try
{
    rs->Open(CRecordset::snapshot, "SELECT USER FROM DUAL;");
}
catch (CException *pe)
{
    pe->Delete();
}
Avatar of jmnolan
jmnolan

ASKER

Either answer would have worked for me. Thanks!!
If, instead of displaying the error with ReportError, you want to get the error string, you can do it by getting this member from your exception

e->m_strError

Calling CException::GetErrorMessage is better.