Page 1 of 1

'no brainer' with Generic Exceptions..

Posted: Fri Jun 30, 2006 4:26 pm
by Jenk
Hi chaps..

I'm currently fooling around with an ArrayObject class (I've already passed the woe of PHP having an included-with-core ArrayObject etc.)

Obviously a popular exception for this in Java and other such languages is ArrayIndexOutOfBoundsException.

Now because, as most of us know, PHP does not have such pre-defined exceptions, do you guys create an include page with nothing but the 'generic' excpetion classes or do you all create them as per needed within the same file as the class that throws it? (and have a check to see if it has already been defined?)

As I said.. no brainer, I'm knocking up a Generic Exceptions include file now but was wondering what everyone else does :)

For those that do not understand my babble..

Generic exceptions:

Code: Select all

<?php

class ArrayIndexOutOfBoundsException extends Exception {}
class StringIndexOutOfBoundsException extends Exception {}
class NullPointerException extends Exception {}

//etc..

?>
vs:

Code: Select all

<?php

class ArrayIndexOutOfBoundsException extends Exception {}

class MyArrayObject 
{ 

//blah..

/*
*getValue throws ArrayIndexOutOfBoundsException
*/
    public function getValue ($ind = null)
    {
        if (($ind !== null) && (!isset($this->array[(int)$ind])) {
            throw new ArrayIndexOutOfBoundsException ('Index ' . strval($ind) . ' is non-existant');
        }
    }

//blah

}

?>
and secondly.. do you bother using these exceptions? or just have one exception named after the class, or use just plain old Exception?

Posted: Mon Jul 03, 2006 9:08 am
by Ambush Commander
If you would like to use the exceptions without using the object, put them in a seperate file. In this case, what happens if you have a YourArrayObject? But if you have an ArrayObject that is the only array object in town (and uses these exceptions), you may put them there for clarity: after all, that's the only code that will throw those exceptions.

If you do put them in another file, I'd suggest you set up a generic ArrayException. Exception hierarchies allow for some nice specific -> general catching.

Of course, this is purely theoretical. I've never actually used exceptions before. :lol:

Posted: Mon Jul 03, 2006 9:19 am
by Jenk
I would certainly prefer a hierachy of exceptions, but in PHP it's detrimental due to the extensions hit on memory/cpu time :)

The class specific exceptions I have catered for as well, such as malformed arguments, these are defined within the same file as the class, but I was just referring to the 'generic' exceptions such as above and FileNotFoundException etc. :)

My exeption handlers also print the stack trace and all available info, thus it should be easy for myself or future developers to find.