The Right Approach to Exceptions

deadalnix deadalnix at
Sat Feb 18 11:20:23 PST 2012

Le 18/02/2012 19:52, Andrei Alexandrescu a écrit :
> There's a discussion that started in a pull request:
> Let's come up with a good doctrine for exception defining and handling
> in Phobos. From experience I humbly submit that catching by type is most
> of the time useless.
> Andrei

I think your oppinion here is shaped by C++. For what I experienced, in 
C++, exception are only usefull for very important problem you cannot 
possibly solve, and at the best log the error and exit.

An exemple is std::bad_alloc .

However, in D, I think this is more the role of an Errors. Exception are 
something « softer ». It will alert you on problems your program 
encounter, but that are recoverable.

You cannot recover from any exception at any place (sometime, you just 
cannot at all).

Let's get an exemple : your program ask a file to the user and do some 
operations with this file. If the file doesn't exists, you can prompt 
for another file to the user with a meaningful message and start again. 
However, the first version of your program can just ignore that case and 
fail with a less specific handler in firsts versions.

You cannot achieve something like that if you don't have a useful type 
to rely on. Here something like FileNotFoundException is what you want.

The type of the exception must depend on the problem you are facing, not 
on the module that trhow it. I see a lot of people doing the « 
MyProgramException » or « MyLibException » but that doesn't make sense. 
In this case, you are just making things harder.

Back on the original subject, GetOptException is not what you want. As 
getopt is supposed to handle command line parameters, you'll use 
exception like : MissingParameterException, WrongFormatException, 
UnknowParameterException or anything that is meaningful.

Those Exceptions would inherit from something like CommandLineException. 
This is useful because it describe what you are facing. Because you cant 
to know what is the problem, not which piece of code face the problem.

If this politic is choosen, then It would make sense to have several 
modules of phobos throwing exceptions of the same type, or inheriting 
from the same base class.

Exception type is a convenient way to filter what you catch and what you 
don't know how to handle at this point.

More information about the Digitalmars-d mailing list