The Right Approach to Exceptions

Jose Armando Garcia jsancio at
Sat Feb 18 16:21:17 PST 2012

On Sat, Feb 18, 2012 at 9:13 PM, Andrei Alexandrescu
<SeeWebsiteForEmail at> wrote:
> On 2/18/12 4:26 PM, Jonathan M Davis wrote (abridged):
> GetOptException
> FlagArgumentMissingException
> InvalidFlagArgumentException
> UnknownFlagException
> FileException
> FileNotFoundException
> NotFileException
> NotDirException
> AccessDeniedException
> I died inside a little.

Yeah. This gets even worse by the fact that some times you have to
import vendor specific modules with their own set of exceptions. For
example the JDBC exception model was just a nightmare. Depending on
which database driver you used you could have a completely different
set of exceptions you had to catch.

The Spring Framework solved this problem by just throwing just one
exception: SQLException (if my memory serves me right). The developer
then had to switch based on the driver type and the error code. I
don't think this is perfect but I think it works much better in

The other nice thing about this model is that it is easier to know
which error you want to handle. Database vendor document their errors
using error code not language specific exception. If the Oracle manual
says that the database gives error XXXX for such and such condition
how in the world do you know to which JDBC exception does that match
or D exception, etc.?

I'll be the first to suggestion something. One possible solution is to
have one exception and inside have the concept of a namespace and a
error code.

Assuming that D had pattern matching you could do:

try {
} catch (Exception(IONamespace, errorCode)) {
  // errorCode is a variable with the error and the exception must
match the value in IONamespace
} catch (Exception(DBNamespace, AccessDenied) {
  // matches the db namespace and the access denied error code

Destroy. Thanks,

> Andrei

More information about the Digitalmars-d mailing list