The Windows API CopyFile
function is rather straightforward:
BOOL CopyFileW( [in] LPCWSTR lpExistingFileName, [in] LPCWSTR lpNewFileName, [in] BOOL bFailIfExists );
…
If the function fails, the return value is zero. To get extended error
information, callGetLastError
.
However, I found this gem in our C++ source code, dating back to Oct / 2006
:
try { //Exception, if the file already exists and is write protected
bCopyOK = CopyFile(csSourceFile, csDestinationFile, bFailIfExists);
} catch (...) {
bCopyOK = FALSE;
}
I even found the old ticket title (of course without details): "function ‘CopyFile’ throws Exception if Destination is write protected, catch Exception" 🙂
Even today we still compile with /EHa
, so this would have caught any SEH exceptions raised.
Now, at this point in time we would’ve been using Visual Studio 6 on Windows XP, and that one had all kinds of quirks, but still: I have a hard time imagining this function ever raising an exception (apart from invalid/null parameters and such).
2
Answers
// Self answer, with historical perspective.
It is not documented to throw exceptions, as is apparent from the current docs linked above.
Both the other answer and also, e.g. Do DeleteFile() Or CopyFile() throw exceptions? quite definitely assert that there should be no exception being raised.
However, as is mentioned in comments:
and in the linked question:
It is very well possible that the original developer could actually reproduce this behavior on his machine, and swallowing the error "fixed" it well enough back then.
Things have improved since then. Given that no reproduction is possible in current code, and given that this only works with
/EHa
anyways, the try-catch is a candidate for cleanup.NO.
at first not exist SEH exceptions at all. SEH this is type of exception handler but not type of exception. another type of handlers (not exceptions) is VEH.
exception can be raised or via invoke
RaiseException
/RtlRaiseException
/ZwRaiseException
or by CPU. of course CPU exception alwas can be raised (in caselpExistingFileName
orlpNewFileName
for instanse point to invalid memory ) butCopyFileW
never callRaiseException
– by fact and by documentation.so in what problem ? create write protected file
lpNewFileName
and callCopyFile
and test result. will be exception or error code returned