Where to put the error handing test?

alex23 wuwei23 at gmail.com
Tue Nov 24 01:27:24 EST 2009


On Nov 24, 1:15 pm, Peng Yu <pengyu... at gmail.com> wrote:
> Suppose that I have function f() that calls g(), I can put a test on
> the argument 'x' in either g() or f(). I'm wondering what is the
> common practice.
>
> If I put the test in f(), then g() becomes more efficient when other
> code call g() and guarantee x will pass the test even though the test
> code in not in g(). But there might be some caller of g() that pass an
> 'x' that might not pass the test, if there were the test in g().

What you should try to do is make each function as self-contained as
possible. f() shouldn't have to know what is a valid argument for g(),
that's the responsibility of g(). What f() needs to know is how to
deal with any problems that arise while using g().

As a very rough example:

    def g(x):
        try:
            assert isinstance(x, int)
        except AssertionError:
            raise TypeError, "excepted int, got %s" % type(x)
        # ... function code goes here

    def f(x):
        try:
            g(x)
        except TypeError:
            # handle the problem here
        # ... function code goes here

> My thought is that if I put the test in g(x), the code of g(x) is
> safer, but the test is not necessary when g() is called by h().

This sounds strange to me. Are you stating that h() can pass values to
g() that would be illegal for f() to pass? That sounds like a very
dangerous design...you want each function's behaviour to be as
consistent and predictable as it possibly can.



More information about the Python-list mailing list