Re: Best practice concerning Exceptions
| From: | Daniel O'Connor | Date: | Thu, 11 Mar 2010 00:21:52 +0000 |
| Subject: | Re: Best practice concerning Exceptions | ||
| References: | 1 | Groups: | php.pear.general |
| Request: | Send a blank email to pear-general+get-30393@lists.php.net to get a copy of this message | ||
On Thu, Mar 11, 2010 at 1:07 AM, Auke van Slooten <auke@muze.nl> wrote:
> Hi,
>
> I've found the XML_RPC2 package (only after writing my own version of it
> ofcourse :( ..) and noticed that it declares quite a number of different
> exception classes. I've read the 'Error Handling Guidelines for PHP5
> Packages' but couldn't find any information on when to use a new Exception
> class and when simply to use a new code and message.
>
> What is considered good practice for PHP5 exceptions? My own code uses just
> two exception classes, with about 8 different codes and messages. It seems
> the XML_RPC2 package throws a specific exception class for each error,
> skipping error codes.
>
>
I find that most people (myself included) just rely on a general category of
exception; and rarely if ever make use of exception codes.
IE; I'd do:
class Foo {
public function bar($path) {
// Checking to ensure things are 'valid' or 'expected' ->
InvalidArgumentExceptions
if (!file_exists($path)) {
throw new InvalidArgumentException("Path must exist");
}
// Doing the actual business logic; and unexpected things happen
$content = file_get_contents($path);
if (empty($content)) {
throw new InvalidDataException("It looks like the supplied file
is empty");
}
}
}
rather than
throw new FooException("Path must exist", Foo::INVALID_ARGUMENT);
throw new FooException("It looks like the supplied file is empty",
Foo::INVALID_DATA);