PHP5 and Exception handling




Quite some time ago i dropped php4 support on all of my projects and started thinking how i can benefit from PHP5 new features specially the new exception handling system. due to the fact thatPHP4 had no official exception system, programmers had to come up with their own way for handling exceptions properly , one this solutions was PEAR ERROR which i think was very useful, and i think that even thought PHP5 developers no longer need that technique it still can be used for better code quality in various circumstances.

What i'm going write about in this article is how to combine both solutions and the best of both worlds and also how and when to use each solution


Implementing perfect exception handling is much more difficult than it may seem and requires careful thinking and planning from the begining of the project. Picking the wrong solution not only decreases programs stability but also slows down development and troubleshooting bugs

Understanding PHP5's exception handling

As you might already know, exception handling is nothing new. as a matter of fact almost all of the modern programming languages like Java, Python, C++, etc already support this feature in a much more completed way than PHP. so it's a must have feature. lets see how it works.


How to integrate it


When should we throw exception

  • When it's an unexpected behaviour, for example when we include a class and want to make an instance. That class should exists, and if it isn't then there is a serious problem.
  • When it happens application can no longer work properly

Important Question

  • Should we use exception for PHP's built-in errors?
    • No, because chaning default behaviour confuses users

When do we need a new exception class

  • When we want to introduce new speciall properties and methods for a class for better error handling !?

Resources :

Your rating: None Average: 2.4 (8 votes)