I am working with GDAL in Python and have wanted to get GDAL to raise exceptions so that I can do something useful with them. For instance if a file cannot be opened with gdal.Open() I would like to throw an exception instead of gdal returning None. I would just like a way to capture the errors instead of them being dumped to sys.stdout.

Currently I have tried using the gdal.UseExceptions() function but came across an issue. When gdal.UseExceptions() is set it seems to hide certain errors and not raise an exception on them. For instance ERROR 5: Access window out of range in RasterIO() Requested (1,15) of size 25x3 on raster of 26x17 disappears and no exception is raised. This seems pretty dangerous.

Any ideas are appreciated, thanks.

  • 1
    Doug - pretty similar to the question I asked about OGR/Postgres errors this morning (link below). The (hackish) way we handle the GDAL error issue is to set everything that connects to GDAL/OGR to None and then use a custom error class to raise a specific error about the connection, if after the GDAL/OGR operation the value is still None. gis.stackexchange.com/questions/30607/…
    – Tomas
    Jul 31, 2012 at 10:28
  • 1
    I filed a ticket as recommended by the comment below. It can be tracked here : (trac.osgeo.org/gdal/ticket/4800)
    – Doug
    Sep 4, 2012 at 19:23

1 Answer 1

** We do not want to interfere with warnings or debug messages since
** they won't be translated into exceptions.
if (eclass == CE_Warning || eclass == CE_Debug ) {
    pfnPreviousHandler(eclass, code, msg );

The UseExceptions handler doesn't listen to anything other than CE_Error, or CE_Fatal. What you're seeing is probably a CE_Warning or CE_Debug message (check the return value of your functional call to see what it's equal to).

This compromise was made to make sure that the "new" python bindings behaved similarly to the "old" python bindings (which where hand-rolled with all error handling being of the check-the-return type). I agree this kind of sucks.

Feel free to file a ticket so we can add levels for the exception handler to listen to, ala

  • 1
    Thanks for the reply, this totally makes sense and I will try to get to filing a ticket and posting the link here!
    – Doug
    Aug 21, 2012 at 1:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.