I have a problem with my error handling... (Using VS2010Express)
My code looks like this:
#import "C:\Program\Delade filer\System\ado\msado15.dll" rename ("EOF","adoEOF") no_namespace
int main(int argc, char *argv[])
{
_ConnectionPtr pConnection;
_CommandPtr pCommand;
_ParameterPtr pParameter;
_RecordsetPtr 开发者_如何学Go pRecordset;
int iErrorCode;
HRESULT hr;
// Initialize COM
if(FAILED(hr = CoInitialize(NULL)))
{
goto done_err;
}
// more code here .....
// Uninitialize COM
CoUninitialize();
// Everything worked out, report an OK
iErrorCode = 0;
done:
return iErrorCode; ERROR!!
done_err:
// TODO: Cleanup
iErrorCode = (int)hr;
goto done;
At the line marked with ERROR i get a runtime error and the debugger goes into comip.h line 782. I have never used error handling procedures before (ooops) and the above code is not written by me. I understand whats going on, but the "done:" and "done_err:" stuff I have never seen before. If anyone could explain that shortly I would be very thankful.
Regards, Lumpi
'That done: stuff'
is a label and goto
is used to perform a jump, that is continue program execution at a totally different, labeled place within the same function. So in case of an error, execution is continued directly beneath the line that reads done_err:
- after error reporting has been performed, it jumps to the regular return point, which is behind the done:
label.
You have trouble reading it, I have trouble reading it. Everyone has trouble reading it. So:
This is extremely bad practice in C++. Therefore, do not use goto unless you have extremely good reasons.
The same logic could be expressed as follows:
if(FAILED(hr = CoInitialize(NULL)))
{
// HandleError could display a messagebox or print to a log file ...
HandleError(hr);
return hr;
}
// do something meaningful
return 0;
Regarding your crash - there's very little we can do about it. Most likely you're causing some data corruption somewhere (a good guess of mine, having never used this ADO stuff by myself: you are leaking the connection handle, i.e. you don't release it prior to calling CoUnitialize). Check the rest of your code for any flaws, but first get rid of those gotos.
精彩评论