Share via

CException Class

The base class for all exceptions in the Microsoft Foundation Class Library.


class AFX_NOVTABLE CException : public CObject


Public Constructors

Name Description
CException::CException Constructs a CException object.

Public Methods

Name Description
CException::Delete Deletes a CException object.
CException::ReportError Reports an error message in a message box to the user.


Because CException is an abstract base class you can't create CException objects directly; you must create objects of derived classes. If you need to create your own CException-style class, use one of the derived classes listed above as a model. Make sure that your derived class also uses IMPLEMENT_DYNAMIC.

The derived classes and their descriptions are listed below:

Name Description
CSimpleException A base class for resource-critical MFC exceptions
CInvalidArgException Invalid argument exception condition
CMemoryException Out-of-memory exception
CNotSupportedException Request for an unsupported operation
CArchiveException Archive-specific exception
CFileException File-specific exception
CResourceException Windows resource not found or not creatable
COleException OLE exception
CDBException Database exception (that is, exception conditions arising for MFC database classes based on Open Database Connectivity)
COleDispatchException OLE dispatch (automation) exception
CUserException Exception that indicates that a resource could not be found
CDaoException Data access object exception (that is, exception conditions arising for DAO classes)
CInternetException Internet exception (that is, exception conditions arising for Internet classes).

These exceptions are intended to be used with the THROW, THROW_LAST, try, catch, and_catch, and end_catch macros. For more information on exceptions, see Exception Processing, or see the article Exception Handling (MFC).

To catch a specific exception, use the appropriate derived class. To catch all types of exceptions, use CException, and then use CObject::IsKindOf to differentiate among CException-derived classes. Note that CObject::IsKindOf works only for classes declared with the IMPLEMENT_DYNAMIC macro, in order to take advantage of dynamic type checking. Any CException-derived class that you create should use the IMPLEMENT_DYNAMIC macro, too.

You can report details about exceptions to the user by calling GetErrorMessage or ReportError, two member functions that work with any of CException's derived classes.

If an exception is caught by one of the macros, the CException object is deleted automatically; don't delete it yourself. If an exception is caught by using a catch keyword, it isn't automatically deleted. See the article Exception Handling (MFC) for more information about when to delete an exception object.

Inheritance Hierarchy




Header: afx.h


This member function constructs a CException object.

explicit CException(BOOL bAutoDelete);


Specify TRUE if the memory for the CException object has been allocated on the heap. This will cause the CException object to be deleted when the Delete member function is called to delete the exception. Specify FALSE if the CException object is on the stack or is a global object. In this case, the CException object won't be deleted when the Delete member function is called.


You would normally never need to call this constructor directly. A function that throws an exception should create an instance of a CException-derived class and call its constructor, or it should use one of the MFC throw functions, such as AfxThrowFileException, to throw a predefined type. This documentation is provided only for completeness.


This function checks to see if the CException object was created on the heap, and if so, it calls the delete operator on the object.

void Delete();


When deleting a CException object, use the Delete member function to delete the exception. Don't use the delete operator directly, because the CException object may be a global object or have been created on the stack.

You can specify whether the object should be deleted when the object is constructed. For more information, see CException::CException.

You only need to call Delete if you're using the C++ try- catch mechanism. If you're using the MFC macros TRY and CATCH, then these macros will automatically call this function.


CFile* pFile = NULL;
// Constructing a CFile object with this override may throw
// a CFile exception, and won't throw any other exceptions.
// Calling CString::Format() may throw a CMemoryException,
// so we have a catch block for such exceptions, too. Any
// other exception types this function throws will be
// routed to the calling function.
// Note that this example performs the same actions as the
// example for CATCH, but uses C++ try/catch syntax instead
// of using the MFC TRY/CATCH macros. This sample must use
// CException::Delete() to delete the exception objects
// before closing the catch block, while the CATCH example
// implicitly performs the deletion via the macros.
   pFile = new CFile(_T("C:\\WINDOWS\\SYSTEM.INI"),
      CFile::modeRead | CFile::shareDenyNone);
   ULONGLONG ullLength = pFile->GetLength();
   CString str;
   str.Format(_T("Your SYSTEM.INI file is %u bytes long."), ullLength);
catch(CFileException* pEx)
   // Simply show an error message to the user.
catch(CMemoryException* pEx)
   // We can't recover from this memory exception, so we'll
   // just terminate the app without any cleanup. Normally, an
   // an application should do everything it possibly can to
   // clean up properly and _not_ call AfxAbort().
// If an exception occurs in the CFile constructor,
// the language will free the memory allocated by new
// and will not complete the assignment to pFile.
// Thus, our clean-up code needs to test for NULL.
if (pFile != NULL)
   delete pFile;


Call this member function to report error text in a message box to the user.

virtual int ReportError(
    UINT nType = MB_OK,
    UINT nMessageID = 0);


Specifies the style of the message box. Apply any combination of the message-box styles to the box. If you don't specify this parameter, the default is MB_OK.

Specifies the resource ID (string table entry) of a message to display if the exception object doesn't have an error message. If 0, the message "No error message is available" is displayed.

Return Value

An AfxMessageBox value; otherwise 0 if there isn't enough memory to display the message box. See AfxMessageBox for the possible return values.


Here's an example of the use of CException::ReportError. For another example, see the example for CATCH.

CFile fileInput;
CFileException ex;

// try to open a file for reading.
// The file will certainly not
// exist because there are too many explicit
// directories in the name.

// if the call to Open() fails, ex will be
// initialized with exception
// information.  the call to ex.ReportError() will
// display an appropriate
// error message to the user, such as
// "\Too\Many\Bad\Dirs.DAT contains an
// invalid path."  The error message text will be
// appropriate for the
// file name and error condition.

if (!fileInput.Open(_T("\\Too\\Many\\Bad\\Dirs.DAT"), CFile::modeRead, &ex))
  // the file was opened, so do whatever work
  // with fileInput we were planning...


See also

CObject Class
Hierarchy Chart
Exception Processing