Benchmark of try/catch

Daniel Keep daniel.keep.lists at gmail.com
Tue Mar 24 17:02:29 PDT 2009


> I only had a short look, is it the NaN known from floating point types
> generalized to all types?

Not quite; NaNs don't abort your program (ignoring signalling NaNs, of
course.)

> Yay, The Power of None! That's what I was referring to when proposed
> nullable types:
> 
> int? value1 = atoi("0");   // 0
> int? value2 = atoi("#!$"); // null

Not quite; that assumes null isn't a valid value.  What if the function
was "getInstance"?

Here's how I understand it to work.  Functions may return a Maybe!(T),
which is either a T or None (note that None is not null), and is
implicitly castable to T.

Now, let's say we have this:

Maybe!(int) toInt(string);

Suppose we have the following:

void main()
{
    writef("Enter a number: ");
    string num_str = readline();
    auto result = toInt(num_str);
    int num = result;
    writefln("You entered: %d", num);
}

Now, when the program asks for a number, we enter "42".  The program
works exactly as one would expect; no drama.  The Maybe!(int) is
transparently cast to an int.

Next we try entering "get nodded" instead.  toInt doesn't take kindly to
this, and wants to throw an InsultingInputException.  However, it
doesn't actually throw it; it merely constructs the exception and
returns it inside a None value.

So in this case, result is a Maybe!(int) containing a None, wrapping an
Exception.  This is fine.  It's not until the program tries to cast the
result to an int that the exception is thrown.  That is, the exception
is only thrown at the moment we attempt to USE the result and find it's
not valid.

Alternately, we could do this:

void main()
{
    writef("Enter a number: ");
    string num_str = readline();
    auto result = toInt(num_str);
    if( result == None )
    {
        writefln("Error: \"%s\" is not a number.", num_str);
    }
    else
    {
        int num = result;
        writefln("You entered: %d", num);
    }
}

We can directly test a Maybe!(T) to see if it's None; this allows us to
safely work out whether the function failed or not.

The idea behind all this is to allow for exception-style programming
where we don't care about testing for failures (but still want them to
stop our program via an exception) OR C-style programming where we DO
care about a particular function failing, and test the return values.

The nice thing about this is that you either explicitly test for and
handle the error, or it jumps out at you like a spider if you try to
ignore it -- best of both worlds without the risk of missing a failure.

  -- Daniel



More information about the Digitalmars-d mailing list