[gdal-dev] Re: Catch a GDALOpen exception

Mateusz Loskot mateusz at loskot.net
Thu Apr 7 12:53:59 EDT 2011


On 07/04/11 08:04, canduc17 wrote:
> Ok. So if I have well understood the most safe thing to do is the following:
> myDataset = (GDALDataset *) GDALOpen( "myFile.tif", GA_ReadOnly );
> 	if(myDataset == NULL )
> 	{
> 		return 14;
> 	}

Depends on what you consider as "most safe".
In terms of exception safety and safe management of resources in C++,
safe version of your code is:

// Using either C++0x or Boost shared_ptr implementation
typedef std::shared_ptr<GDALDataset> dataset_t;

dataset_t make_dataset(GDALDataset* pds)
{
     dataset_t ds(pds, ::GDALClose);
     return ds;
}

dataset_t open_dataset(char const* const file)
{
     dataset_t ds(make_dataset(
         static_cast<GDALDataset*>(
             ::GDALOpen(file, ::GA_ReadOnly))));
     if(!ds)
     {
         // or return ds and let user to test against nullptr
         throw std::runtime_error("failed to open dataset");
     }
     return ds;
}

dataset_t myDataset(open_dataset("myFile.tif"));
// if open_dataset throws, no need to test against nullptr

Best regards
-- 
Mateusz Loskot, http://mateusz.loskot.net
Charter Member of OSGeo, http://osgeo.org
Member of ACCU, http://accu.org


More information about the gdal-dev mailing list