[gdal-dev] Catch a GDALOpen exception
Even Rouault
even.rouault at mines-paris.org
Wed Apr 6 13:53:22 EDT 2011
Le mercredi 06 avril 2011 18:09:42, Howard Butler a écrit :
> 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;
> >
> > }
This cannot work. The C (and C++) API of GDAL doesn't throw C++ exceptions.
>
> You need to implement your own error handler if you want GDAL to throw
> exceptions when it can open something.
I would recommand *against* doing that. Throwing exceptions from the GDAL
error handler can lead to memory leaks and/or file descriptor leaks because the
GDAL drivers will not be able to release memory/file descriptors (there's no
guarantee that the GDAL error is emitted before the cleanup of ressources has
been done).
You can simply test that the handle returned by GDALOpen() is not NULL. And
you can also call CPLGetLastErrorMsg() / CPLGetLastErrorType() after the
GDALOpen() call.
Or If you really want to use your own error handler, you can use it to store
the error into some list for example and examine it afterwards.
>
> 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_______________________________________________
> gdal-dev mailing list
> gdal-dev at lists.osgeo.org
> http://lists.osgeo.org/mailman/listinfo/gdal-dev
More information about the gdal-dev
mailing list