# Solved: Application Throws Exception On Exit From Main



## pcpro17 (Oct 9, 2006)

My MFC Console application is throwing an error when exiting, after handling a caught exception.



> Exception: 997
> Overlapped I/O operation is in progress.


Inside `main` I have this exception handling routine (among others, but it is only after processing this exception that this bizarre error occurs):


```
catch( CExceptionHandler * ex )
    {
        CDumpFile file;
        wchar_t * pBuf = NULL;
        CString cs;

        wcout << _T("Dumping exceptional data . . . ") << endl;
        afxDump.m_pFile = &file;
        ex->Dump( afxDump );

        FormatMessage(
            FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
            NULL,
            ex->m_dwError,
            MAKELANGID(LANG_NEUTRAL,
            SUBLANG_SYS_DEFAULT),
            (LPTSTR)&pBuf,
            0,
            NULL);
        cs.Format( L"%d", (int)ex->m_dwError );
        ex->Delete();

        wcout << _T("Exception: ");
        wcout << (LPCTSTR)cs << endl << pBuf << endl;
    }
```
Finally, as the application exits, this exception is thrown:



> Unhandled exception at 0x78a54b12 (mfc90ud.dll) in CppTestConsole.exe: 0xC0000005: Access violation reading location 0x0000003f.


Specifically, the exception is thrown when the closing brace `}` of main is being executed. I've pasted the call stack below, if it's useful.



> mfc90ud.dll!CDumpContext:perator<<(const wchar_t * lpsz=0x0012a724) Line 82 + 0x25 bytes	C++
> mfc90ud.dll!CDumpContext:perator<<(const char * lpsz=0x0012cb9c) Line 396	C++
> mfc90ud.dll!_AfxCrtReportHook(int nRptType=0, char * szMsg=0x0012cb9c, int * pResult=0x0012ab70) Line 108	C++
> msvcr90d.dll!_VCrtDbgReportA(int nRptType=0, const char * szFile=0x00000000, int nLine=0, const char * szModule=0x00000000, const char * szFormat=0x102148e4, char * arglist=0x0012fc28) Line 358 + 0x1d bytes	C
> ...


Thanks.


----------



## pcpro17 (Oct 9, 2006)

The problem was caused by improper declaration, instantiation, and cleanup of a class object. After moving the declaration and cleanup outside of the `try`/`catch` blocks, the problem went away.


----------

