try/catch idiom in std.datetime

Timon Gehr timon.gehr at gmx.ch
Mon Nov 18 15:20:31 PST 2013


On 11/18/2013 11:45 PM, Andrei Alexandrescu wrote:
> On 11/18/13 2:04 PM, Walter Bright wrote:
>> On 11/18/2013 1:02 PM, Jacob Carlborg wrote:
>>> I really don't understand the point in having some functions thrown
>>> and others
>>> assert.
>>
>> That's a red flag that there is a faulty design somewhere, in this case
>> I think it's not having a separation between input data validation and
>> program bug detection.
>
> The question is what's "program" and what's "input". Consider:
>
> int a = fun();
> std.gun(a);
>
> There are two possible takes on this:
>
> 1. The standard library is considered part of the user's program, and
> the whole thing is a unit. In that case, passing the wrong int to
> std.gun is an PROGRAM error and 100% blame goes to the programmer who
> wrote the caller code. In that case, assert/assert(0)/contracts are the
> appropriate constructs to be used inside std.gun.
>
> This is the approach taken by the C standard library, which is free to
> do whatever it wants (including crashing the program) upon calls such as
> strlen(NULL) etc.
>
> 2. The standard library is a separate entity from the PROGRAM, and as
> far as it cares, any data from the user is INPUT. So the standard
> library with SCRUB the input, in which case enforce() and throwing
> exceptions are appropriate.
>
> This is the approach taken by the Windows API, Java, C#, and to a good
> extent the newer parts of C++'s standard library.
>
> To claim that one approach is exactly right and the other is exactly
> wrong would miss important insights.
>...

1. Has the shortcoming that you may actually get assertion failures.

2. is not wrong but aesthetically unpleasing as it essentially widens 
the interface to allow all possible inputs and extends it with behaviour 
that is useless in order to avoid the situation that the caller does not 
satisfy the interface. There is also:

3. Require both caller and callee to construct a compile-time checkable 
proof that they satisfy their part of the interface.

This is the approach taken by dependently typed programming languages, 
and program verifiers. This subsumes 1. and 2. and is a solution to the 
original problem since in such a setting it can be manually proven that 
a function call will not throw.


More information about the Digitalmars-d mailing list