Return to Snippet

Revision: 38431
at January 2, 2011 15:53 by MartinYork


Initial Code
#include <iostream>
#include <stdexcept>

struct SpaceWaster {
    SpaceWaster(int l, bool b, SpaceWaster *p) : level(l), bad(b), prev(p) {}
    // we want the destructor to do something
    ~SpaceWaster() { prev = 0; }
    int checkLevel() { return level == 0;}
    int isBad() {return bad;}
    int level;
    bool bad;
    SpaceWaster *prev;
};

void thrower(SpaceWaster *current) {
    if (current->checkLevel())
    {
        if (current->isBad())
            throw std::logic_error("some error message goes here\n");
        return;
    }
    SpaceWaster next(current->level - 1,  current->isBad(), current);
    // typical exception-using code doesn't need error return values
    thrower(&next);
    thrower(&next);
    thrower(&next);
    return;
}

char const*     errorMsg;

char const*     errorMsg;

int returner(SpaceWaster *current) {
    if (current->checkLevel())
    {
        if (current->isBad())
        {
            errorMsg    = "some error message goes here\n:";
            return -1;
        }
        return 0;
    }
    SpaceWaster next(current->level - 1, current->isBad(), current);
    // typical exception-free code requires that return values be handled
    int result = returner(&next);
    if (result == 0)
    {
        result  = returner(&next);
    }
    if (result == 0)
    {
        result  = returner(&next);
    }
    return result;
}

int main()
{
    const int repeats = 1000;
    int returns = 0;
    int fails   = 0;

    for (int i = 0; i < repeats; ++i)
    {
        SpaceWaster first(10, (i%100) == 0, 0);
#ifdef THROW
        try
        {
            thrower(&first);
            ++returns;
        }
        catch (std::exception &e)
        {
            ++fails;
        }
#else
        if (returner(&first) == 0)
        {
            ++returns;
        }
        else
        {
            ++fails;
        }
#endif
    }
    std::cout << fails << ":" << returns
#ifdef THROW
    << " exceptions"
#else
    << " returns"
#endif
    << "\n";
}

[Alpha:~] myork% g++ -DTHROW t.cpp
[Alpha:~] myork% time ./a.out
10:990 exceptions
1.275u 0.001s 0:01.27 100.0%	0+0k 0+0io 0pf+0w


[Alpha:~] myork% g++  t.cpp
[Alpha:~] myork% time ./a.out
10:990 returns
1.325u 0.003s 0:01.33 99.2%	0+0k 0+0io 0pf+0w

Initial URL


Initial Description


Initial Title
Exceptions Vs Returns

Initial Tags
c++

Initial Language
C++