enforce()?

Jonathan M Davis jmdavisProg at gmail.com
Wed Jun 16 11:03:09 PDT 2010


Andrei Alexandrescu wrote:

>> Anyway, I think enforce() is poisson,
> 
> Indeed it is a bit fishy :o).

LOL. My thoughts exactly.
> 
>> because it make the programmer to
>> not think about errors at all, just add and enforce() and there you go.
>> But when you need to be fault tolerant, is very important to know what's
>> the nature of the error, but thanks to enforce(), almost every error is
>> a plain Exception, no hierarchy, no extra info, all you can do to get
>> a little more info about what happened is to parse the exception string,
>> and that's not really an option.
> 
> I think there is no real need for exception hierarchies. I occasionally
> dream of eliminating all of the useless exceptions defined left and
> right in Phobos.
> 
>>> And in fact, I think there's an errnoEnforce which throws a standard
>>> exception with the string error from the system.
>> 
>> That's the only useful case of enforce, because it includes the
>> *important* information (the actual errno).
>> 
>> There is also enforceEx!(), to use a custom exception, which practically
>> nobody uses (I counted only 4 uses in phobos).
> 
> I'd be hard pressed to find good examples of exception hierarchy use.
> Everybody talks about them but I've seen none.
> 
> The fact that the coder doesn't need to think hard to use enforce()
> effectively is a plus, not a minus. An overdesigned enforce that adds
> extra burden to its user would have been a mistake.
> 
> 
> Andrei

I think that exception hierarchies can be quite useful, but in most cases, I 
haven't seen projects bother with them. I do think that certain types of 
exceptions can be useful as separate types as long as they inherit from the 
base exception type and you therefore don't _have_ to worry about the 
hierarchy.

A good example of a useful exception type IMO is Java's IOException. It 
makes good sense to handle them in a specific way separate from general 
exceptions. You can frequently recover just fine from them, and it allows 
you to handle I/O-related exceptions gracefully while other exceptions might 
be considered fatal. However, those other exceptions - especially those 
which are from more or less unrecoverable errors NullPointerExceptions or 
OutOfMemoryExceptions - don't necessarily gain much from an exception 
hierarchy. So, I think that it really depends on the exception.

I do think, however, that there are certain types of exceptions which can 
benefit from having their own type because it allows you to handle them in a 
specific manner separate from general and/or unrecoverable exceptions.

- Jonathan M Davis


More information about the Digitalmars-d mailing list