Link to home
Start Free TrialLog in
Avatar of edc
edc

asked on

CFileException problem

Hello all,
   I have the following code (snippet)

...
CFile szTemplateFile;
CFileException* pFileError;
CString ErrorText;

if (! szTemplateFile.Open(m_szTemplateParameterData, CFile::modeRead | CFile::shareDenyWrite, pFileError))
{
     FileErr.Clear();
     ErrorText = "Can not open file " + m_szTemplateParameterData;
     FileErr.m_lpszErrorDescription  = ErrorText;
     FileErr.m_nErrorCode = pFileError->m_cause;
...

When I pass a valid file name into the function I don't have any problems.  When I pass an invalid file name into the function I get an unhandled exception error, and I find that pFileError has no information in it.  Any ideas as to what I am doing wrong?

Thanks



Avatar of jkr
jkr
Flag of Germany image

You don't catch the exception - use

TRY {
if (! szTemplateFile.Open(m_szTemplateParameterData, CFile::modeRead | CFile::shareDenyWrite, pFileError)) {
// error
}
CATCH( CFileException* pFileError){
    FileErr.Clear();
    ErrorText = "Can not open file " + m_szTemplateParameterData;
    FileErr.m_lpszErrorDescription  = ErrorText;
    FileErr.m_nErrorCode = pFileError->m_cause;
}
Avatar of edc
edc

ASKER

Thanks for the reply jkr.  I found that if I declare CFileException pFileException rather than CFileException* pFileException and then pass the address to the CFile::Open function that it works, although it would be nice to know why.  I will try your suggestion as well.  It never hurts to have more than one way of doing things.
ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

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
...although it would be nice to know why.

The reason is that in this line,

   CFileException* pFileError;

you declare pFileError as a pointer, but it doesn't point to anything.  If you want to use it that way, you could have used:

CFileException* pFileError= new CFileException;

Thuse, in the call to

.... Open(..., pFileError)...

you were passing an invalid pointer in to the Open call.  That caused an unhandled exception when the system tried to write some data to that address.  I'm thinkijng that the CFileException that is handled by MFC's Open fn handles regular, file-related exceptions, but not memory access exceptions.

As jkr says, the normal way to handle this is something like ...

CFileException e;
BOOL fRet=  .... Open(..., &e );
if (fRet==FALSE ) { // ERROR!!!
      char buf[256];
      e.GetErrorText( buf, sizeof(buf) );
      AfxMessageBox( buf );
}
 
-- Dan