[gdal-dev] Catch a GDALOpen exception

Howard Butler hobu.inc at gmail.com
Wed Apr 6 12:09:42 EDT 2011


On Apr 6, 2011, at 11:04 AM, canduc17 wrote:

> I have this incorrect code:
> try
> 	{
> 	myDataset = (GDALDataset *) GDALOpen( "myimg", GA_ReadOnly );
> 	}
> 	catch(int n)
> 	{
> 		cout << "File not existent!" << endl;
>                return 14;
> 	}
> 


You need to implement your own error handler if you want GDAL to throw exceptions when it can open something.

The following example throws an error if there was a CE_Failure or CE_Fatal and merely puts out the debug message if there is debug info.

> #include <gdal.h>
> #include <stdexcept>
> #include <sstream>
> #include <iostream>
> void CPL_STDCALL HobusGDALErrorHandler(CPLErr eErrClass, int err_no, const char *msg);
> 
> void CPL_STDCALL HobusGDALErrorHandler(CPLErr eErrClass, int err_no, const char *msg)
> {
>     std::ostringstream oss;
>     
>     if (eErrClass == CE_Failure || eErrClass == CE_Fatal) {
>         oss <<"GDAL Failure number=" << err_no << ": " << msg;
>         throw exception(oss.str());
>     } else if (eErrClass == CE_Debug) {
>         std::cout << "GDAL Debug: " << msg << std::endl;
>     } else {
>         return;
>     }
> }

Hope this helps,

Howard


More information about the gdal-dev mailing list