Quantcast

Exception Handling in PHP

Exceptions are the pieces of code which are used to alter the normal flow of the code if a certain error occurs. The concept of exceptions is being used in almost all high level languages. Whenever an exception occurs, the current code state is saved and code execution is switched to a predefined (custom) exception handler function. Depending on the situation, the handler may then resume the execution from the saved code state, terminate the script execution or continue the script from a different location in the code.

Several methods can be utilized to handle the exceptions. In the most basic use of exceptions, when an exception is thrown, the code following it will not be executed, and PHP will try to find the matching “catch” block. If, however, an exception is not caught, a fatal error will be issued with an “Uncaught Exception” message. Following piece of code would throw an exception without catching it:

Since the exception is not caught in the above code, it would receive an error like:

Fatal error: Uncaught exception ‘Exception’

‘Value must be 1 or below’ in C:\webfolder\example.php:6

The second way is to avoid the above problem and catch the exception. For this purpose, the code should include a special function ‘try’. A function using an exception should be in a “try” block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is “thrown”. Second important piece is that of ‘throw’. This is how you trigger an exception. Each “throw” must have at least one “catch”. Finally, the third requirement is ‘catch’. A “catch” block retrieves an exception and creates an object containing the exception information. Here’s the more valid code after the necessary modifications:

The error generated by the above code would be:

Message: Value must be 1 or below

So basically, what we observe is that including a proper exception code with ‘try’ and ‘catch’ pinpoints the error rather than generating some sort of fatal error and hence makes the overall coding process much simpler.

Looking for a quality hosting service? here are a few I suggest.
BlueHost | HostGator | Media Temple