Re: Exceptions: Error Codes Vs Class Names

From: Date: Sat, 28 Aug 2004 15:41:02 +0000
Subject: Re: Exceptions: Error Codes Vs Class Names
References: 1 2  Groups: php.pear.dev 
Request: Send a blank email to pear-dev+get-32996@lists.php.net to get a copy of this message
Justin Patrin wrote:
On Fri, 27 Aug 2004 23:45:50 -0400, Davey <davey@php.net> wrote:
Hey PEARs, Greg, I am not trying to start another debate, I just want to state some facts! I have done some benchmarking with some fake code, one using a single class with a class constant for each type of error, and one using a seperate class for each type of error. I chose the rather random number of 30 errors in each case (so in the first there was 30 constants and the second 30 classes). I ran the random scenario that error 17 was thrown in each case, and caught it. My findings are this: The definition of a single class with 30 constants is about 4 times faster than of the 30 seperate classes, however: because with the single class we have to check the error code using: catch (errors $exception) {
    if ($exception->getCode() == exception_class::CONST) {
        echo $exception;
    }
} as opposed to with the other method which means only the error we want to check for is caught: catch (error17 $exception) {
    echo $exception;
} it turns out to be *marginally* faster. Therefore, the only issue we need to work out is, what if what we're "try{}ing" can throw more than one exception? i.e. we're connecting to a DB, running a query, checking the result - thats 3 seperate errors. With the single class, we have one catch block. With the seperate classes, we need three catch blocks, or we need a parent class. Now, whilst we have a default parent class (Exception) catching all of these (or just our own parent class) means we need to do if ($exception instanceof Error17) which presumably will make it slower (not tested that far yet). But from my initial findings, I would say that by grouping errors into relevant single classes (either per package, or for each large procedure (i.e. user login)) is the fastest and most efficient way to do it. This is the first point I've disagreed with you upon Greg, I hope that cold hard facts will persuade you (and everyone else) that perhaps seperate classes is not the way to go. Certainly I hope this at least shows we need more testing before deciding which way to go.
Ok, I can accept that the single class is faster. If we use that, how will re-throwing work? I suppose we can wrap the exception (as stated in the RFC), but this means: 1) 2 objects instead of 1 will be in that throw now. 2) Another object instatiation due to the above 3) another call to throw, due to the above 4) Possibly re-setting the code
catch (errors $e) {
    throw $e;
}
Whereas if you catch the specific error you want, it will bubble-up automatically.
- Davey

« previous php.pear.dev (#32996) next »