简体   繁体   中英

Possible exception thrown by CFile in MFC Library

Currently, I am investigating some code that uses the CFile class from the MFC Library to open a text file.

I found two kinds of error handling in the code: This are just sample since it is confidential to post the code.. Just think that the body of the try statement contains only member functions of CFile class.

1

try {
     if(file.Open(strPath,Cfile::modeRead|CFile::shareDenyNone)){
     file.Read(strKey, dataLength);
     file.Close();

   }
}
catch (CFileException& e) {
}

2

try {
    // same code above
}
catch (CFileException *e) {
}
  1. What is the difference between the two kinds of exception handling?
  2. What are the possible errors that can be thrown by member functions of the CFile class?
  3. Is no. 1 way possible for catching exceptions thrown by a member function of the CFile class?

You can throw exception objects in two ways, by value:

CException ex;
throw ex; // CException 

or by pointer:

CException *ex = new CException();
throw ex; // CException *

When catching the exception, you catch the corresponding type of what has been thrown, that is, a pointer, or a value. To avoid a copy, we usually catch-by-value using a reference:

catch(CException &e) // when throwing CException

MFC throws exceptions by pointer; see https://msdn.microsoft.com/en-us/library/0e5twxsh.aspx

try {
   AfxThrowUserException();
}
catch( CException* e ) {
   e->Delete();
}

Don't forget do delete the exception afterwards, or you get a small memory leak each time an exception is thrown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM