[Gdal-dev] Exception class(es) in SWIG C# wrapper

Richard Matsunaga richard.matsunaga at waypointinfo.com
Tue Mar 6 09:25:37 EST 2007


> -----Original Message-----
> From: Tamas Szekeres [mailto:szekerest at gmail.com] 
> 2007/3/5, Richard Matsunaga <richard.matsunaga at waypointinfo.com>:
> >
> > If I remember correctly, many times in GDAL, a (C API) method will 
> > return null when something could not happen, like opening a dataset.
> >
> > In these cases, I would like to check for null and throw a 
> > GdalException or OgrException, which contains the extended 
> error message, up my call stack.
> >
> > I could retrieve the error information and send that in any 
> exception, 
> > like an InvalidOperationException, but it's a little 
> cleaner if we can 
> > encapsulate the message details in new exception type.
> >
> Here's the typical SWIG generated error handling code that 
> follows a method invocation.
> result = (GDALDatasetShadow *)Open((char const *)arg1,arg2);
>     CPLErr eclass = CPLGetLastErrorType();
>     if ( eclass == CE_Failure || eclass == CE_Fatal ) {
>       {
>         SWIG_CSharpException(SWIG_RuntimeError, 
> CPLGetLastErrorMsg()); return 0;
>       };
>     }
> SWIG_CSharpException will create a new ApplicationException 
> that will include the string returned by 
> CPLGetLastErrorMsg().  The exception is thrown when the C# 
> function returns.

That's interesting. Are you saying that any time there is an error, an
exception will be thrown? I obviously haven't done enough testing yet to
have tried a failure case.

Also worth noting is that Microsoft (and others) recommend against using
ApplicationException, and especially deriving from it. A search will find
many resources, but here is one:


> Apparently this is a similar operation you have described 
> above. In my understanding the main difference is that you 
> would want to get a different exception type for the 
> different modules.

That's not really what I meant. It wouldn't really matter if there is a
single exception type for both GDAL and OGR or separate ones, although since
they are in different namespaces, the exception would need to be at the root
OSGeo or one would have to reference the other.

My main point is rather than throwing a generic exception type
(System.Exception or System.ApplicationException), having a GDAL/OGR
exception type would enable the exception handlers to intelligently process
errors from GDAL/OGR differently than all other exceptions of type
System.Exception. This is not always necessary, but very powerful if


More information about the Gdal-dev mailing list