This article is the second part of PHP Exception articles. In the previous one, I've written about Exceptions, I've showed you the basic usage and I've provided some examples. It won't be different this time, but I'm going to be a little more advanced. This article is about how to write your own classes.
Reminder: Exception is a special condition that changes the normal flow of the code.
You can extend the core exception class in PHP to have your own class which will suit for the given tasks ahead. It's a good way for categorisation of errors. What I mean is, you can make input exceptions, error exceptions, email exceptions. Another example is if you use the MVC programming pattern, you can make classes related to each layer as follows: ModelException, ViewException, ControllerException. After this, you can extend more classes depending on the occuring errors in each layer.
But let's return from programming patterns to the example code below. Take a look at it. :)
I've defined three new exceptions, and I've also written a class where these exceptions appear. Notice the multiple catch blocks. You have to catch all kind of exceptions by making catch blocks for each of the classes. If an exception occurs you can make the necessary steps in each of the blocks to set variables, warn the user, log or notify someone.
You can also add your custom properties and methods to an extended class. But be careful with this! I say this because if you add a method to your exception class that uses an object - for example email - and you throw this exception in a context where that object is not available or currently not loaded, you're shot and you can start debugging and hacking. Please, prevent this and design your application correctly. The code:
Deciding to use exceptions is a good start to make your application more logical, more understandable and what is much more important, more flexible.