Re: how to store text in a cedit window to file
On Aug 7, 4:14 pm, Joseph M. Newcomer <newco...@flounder.com> wrote:
The chances that WriteString will throw an exception are nonzero, but van=
ishingly small.
The chances that Open (implicit in the constructor) will fail begin to ap=
proach unity.
****>For example, if the code in question is somewhere in a normal MFC
message loop, there is no problem whatsoever: CFileException is
thrown, it bubbles up to CWinThread::ProcessWndProcException and gets
displayed with pException->ReportError(). Peachy.
****
So instead of telling the user that there is a file open error, giving th=
e name of the
file, and the description of the error, "uncaught exception" is considere=
d sufficient
error reporting? I Don't Think So.
joe
****
Hey, I agree that any other problem except failure to open the file
ain't gonna happen. That was just me being purist there.
You are, however, wrong about the uncaught exception (under conditions
I mentioned, of course).
It's easy to verify, try this: in an an empty MFC project, add e.g.
OnEditCopy
void CMainFrame::OnEditCopy()
{
CStdioFile(_T("totally_bad_file_name"),
CFile::modeWrite).WriteString(_T("this can't get written to file,
however, there's no uncaught exception"));
}
You get a message box saying "totally_bad_file_name was not found.",
no memory or other resource leak, no problem whatsoever, let alone
unhandled exception. Note also that if I do this:
void CMainFrame::OnEditCopy()
{
CStdioFile(_T("C:\\ReadOnlyFile.txt"),
CFile::modeWrite).WriteString(_T("this can't get written to file,
however, there's no uncaught exception"));
}
I get this:
Access to C:\ReadOnlyFile.txt was denied.
Isn't it better to use errors provided by MFC than roll your own?
Would you go as far as to detect _why_ something failed? Well, MFC did
("not found" vs. "access denied", with the file name an' all).
But!! For example, if I was to do the above in, say, InitInstance, I'd
get unhandled exception :-(. But then, it should be noted that it's
__BOOL__ CWinApp::InitInstance. MFC must be be obeyed, and so, if it
says that the function returns BOOL, we better return BOOL. OnEditCopy
is, however, void, so escaped exceptions are perfectly valid.
So, for InitInstance and such, one could to this:
inline BOOL
StdExceptionHandlingForMFCOverridesThatMustReturnBOOL(CException* pe)
{
pe->ReportError();
pe->Delete();
return FALSE;
}
BOOL CMyApp::InitInstance()
{
try
{
// A lot of work to initialize the app, without any worry
whatsoever about exceptions
// (except knowing how to write exception-safe code)
return TRUE;
}
catch(CException* pe)
{
return StdExceptionHandlingForMFCOverridesThatMustReturnBOOL(pe);
}
}
There's more than one way to skin a cat ;-)