COM methods return an HRESULT to signify the success or failure of a call, as discussed in the Developing with ArcObjects section of the help system. When you are programming with the C++ API you should check the returned HRESULT of all calls to COM objects.
There are a few common HRESULTs that can be returned.
- S_OK signifies success.
- E_FAIL indicates a failure.
- E_NOTIMPL indicates a method is not implemented.
There are some macros that can be used to test the returned HRESULT.
- bool FAILED(HRESULT)
For example, if the opening of a workspace in which you want to process data fails, you will not be able to use the data. At that point, you should exit the application to avoid a crash later on.
// Open the workspace
IWorkspaceFactoryPtr ipWorkspaceFactory(CLSID_RasterWorkspaceFactory);
IWorkspacePtr ipWorkspace;
HRESULT hr = ipWorkspaceFactory->OpenFromFile(inPath, 0, &ipWorkspace);
if (FAILED(hr) || ipWorkspace == 0)
{
std::cerr << "Could not open the workspace." << std::endl;
return E_FAIL;
}
- bool SUCCEEDED(HRESULT)
For example, if you are going to create a new raster dataset, you must first know that no dataset already exists with the desired name. To find out if such a dataset exists, try to open it. If it succeeds, you know that you cannot create a new dataset with that name.
// Check for existence of a dataset with the desired output name.
// If such exists, we can't create a new one with the name.
IRasterDatasetPtr ipExistsCheck;
hr = ipRastWork->OpenRasterDataset(outFile, &ipExistsCheck);
if (SUCCEEDED(hr))
{
std::cerr << "A dataset with the output name already exists!" << std::endl;
return E_FAIL;
}
In Sample Code and Scenarios
You might notice that the samples and scenarios do not follow the Good Error Handling practices outlined here. This is done simply to increase code readability since error checking is not the focus of those bits of code.