[Gdal-dev] GDAL CPLError and C++ Exceptions

Ray Gardener rayg at daylongraphics.com
Wed Nov 29 06:38:29 EST 2006

fwiw, for those preferring exception-based error reporting all around:

Since GDAL implements return code based error reporting, if you don't 
mind wrapping the GDAL APIs, you can create an exceptions-based 
interface, e.g. if using the GDAL C++ API:

class GDALDataset_plus
     // After normally instancing a dataset, instance a myDataset
     // and assign the original dataset to this member var
     // (or if instancing locally, use the second ctor).
     GDALDataset* m_pDataset;

     GDALDataset_plus() : m_pDataset(NULL) {}
     GDALDataset_plus(GDALDataset* p) : m_pDataset(p) {}
     virtual ~GDALDataset_plus() { if(m_pDataset) delete m_pDataset; }

     void AddBand(type, options)
         if(CE_None != m_pDataset->AddBand(type, options))
            throw gdal_exception();

     // ... wrappers around remaining GDALDataset methods

// ... GDALxxx_plus class versions of remaining GDAL classes

And then you can do stuff like:

   GDALDataset dataset_org;
   GDALDataset_plus dataset(&dataset_org);
      dataset.AddBand(type, options);
      // other stuff, with no checking of return codes
      // since the _plus classes return 'void'
   catch(gdal_exception& e) { msg("GDAL exception occurred"); }
   catch(...) { msg("Unknown error"); }

The wrappers can also be standardized and, if maintained, offered as a 
standard component of the library for those wanting an exception-based 
system. Then one could #include "gdal_plus.h", etc.

The wrappers also enable other niceties, like avoiding having to include 
error variables as arguments (if you always prefer such cases to just 
throw an exception instead), and having the return type of a function 
always be non-error-related. e.g.,
   int foo(void) instead of errcode foo(int* p)


More information about the Gdal-dev mailing list