Developers/Object oriented programming in PHP/Exceptions/en

Exceptions are a great way in OOP to deal with errors. It enables you to handle errors occurred in the called methods in one catch block instead of being forced to check the return value of every method call:

When exception should be used and when not
If you encounter an unexpected condition in your code that can't be handled in your method, then it's best to throw an exception and let the calling method (or up to the initial script) to care about this. The above one is a good example for this: It expects a product item but gets something that doesn't implement the product item interface. Thus, it doesn't know what can be done with this object and before calling a method of the object that doesn't exist (which would result in a fatal error), it throws an exception.

On the other hand, PHP built-in functions usually don't throw any exceptions, so problems can't be handled within a catch block. But there are also cases where you shouldn't throw exceptions and handle problems differently. An example are errors that are not uncommon and can be handled within the same method:

The example method sets the type for each entry in the $values array. If no one is available, no type is added to that value and it doesn't make sense to throw an exception here when it's not required that every entry must have a type. This is also applicable to methods that are likely to fail, because then it's easier to check it's return value in the calling code than wrapping a try/catch block around the single method call.

Exceptions in Arcavias
The Arcavias code uses specific exceptions per domain, e.g. all exceptions thrown in the code of the product domain are objects of the MShop_Product_Exception class extending the MShop_Exception and indirectly the PHP build-in Exception class. Thus, it's possible to create catch blocks for each domain or for all MShop related code:

Important: Messages passed to exceptions must always be formatted with sprintf to enable the translation of the message strings with the GNU gettext</tt> tools.