The Right Approach to Exceptions

deadalnix deadalnix at gmail.com
Sun Feb 19 14:58:19 PST 2012


Le 19/02/2012 17:48, Andrei Alexandrescu a écrit :
> On 2/19/12 10:40 AM, Jacob Carlborg wrote:
>> The command could be in the exception. Then you would have to look it up
>> against all valid commands. For the command to be in the exception you
>> would need some sort of hierarchy because, as others have said, a
>> command property wouldn't make sense for an exception like FileNotFound,
>> and wouldn't make sense in the base class Exception.
>
> Definitely, no argument there! To restate: all I want is to find ways to
> figure the "right" number of exception types, and the "right" primitives.
>
> Andrei

Well that must be decided on each case.

I think the guideline should be to create a new type when the cause of 
the exception is useful for the user when it come to handling it.

For exemple, on a remove function, you want to have 
FileNotFoundException specifically. Even if you do if(file_exists(file)) 
remove(file); a concurent delete can occur.

But if your goal is to delete the file, constating that the file is 
deleted may not be a major problem to you. However, if this operation 
fail because you don't have access to this file, it is a very different 
issue, because the file is still here and you still want to delete it.

The policy should be something along the line « if it make sense to 
handle this problem differently than other problems that can occur, then 
it deserve its own type »

I would add that, by thinking at your proposal of exception that may 
succed if you retry the same thing, phobos should propose a retry 
function that take as parameter a closure and and limit and will retry 
the operation until it succeed or that the limit is reached.

The more I think of it, the more it make sense to have a property on 
Exceptions to explicit if a retry may help.


More information about the Digitalmars-d mailing list