Am 17.03.2011 02:07, schrieb Andrei Alexandrescu:
On 03/16/2011 06:45 PM, bearophile wrote:
- Where it is used it usually doesn't give a more meaningful exception
like WrongArgumentException, etc. I don't want a deep hierarchy of one
hundred standard exceptions, but I think some standard exceptions for
the most common mistakes, like wrong arguments, etc, are better than a
generic enforce(), especially for a standard library code that is
meant to be written with care and to give better error
messages/exceptions.
enforce helps such idioms, does not prevent them. From the docs:
===============
T enforce(T)(T value, lazy Throwable ex);
If value is nonzero, returns it. Otherwise, throws ex.
===============
Really?
using enforce with a custom throwable saves *one* char:
enforce(foo, new BlaException("bad!"));
if(!foo) throw new BlaException("bad!");
or are there other merits?
But using enforce with a custom message (thus it'll just throw a
standard Exception with that message), like assert, really shortens things:
enforce(..., "bad!");
if(!...) throw new Exception("bad!");
So of course enforce allows to throw meaningful exceptions, but it
doesn't make it considerably easier/shorter.
Cheers,
- Daniel