Exception Handling in PHP


An exception is one type of object that is generated in the script because of some unexpected conditions Such as
(1) A user has entered invalid input.
(2) A file that needs to be opened cannot be found or deleted by other user.
(3) A network connection has been lost in the middle of communications.
Some of these exceptions are caused by user’s mistake, some by programmer’s mistake, and some by physical resources.
When such conditions arise in the script an object is created which represents the exception condition and this object is thrown by the system to the calling method. This thrown object is handled by the built in exception handling mechanism supported by PHP.
The built in exception handler of PHP then handles such exception and display the description about the exception condition as shown below:

     

The problem with built in exception handling is that the execution of the script is terminated when such condition is arising.
However it is also possible to display the description of the exception condition without terminating the execution of the script. To do so PHP provides manual exception handling mechanism using following three keywords:
(1) Try
(2) Catch
(3) Throw

Syntax:
try
{
// code to be executed
throw new Exception(“Error Message”);
}
catch (ExceptionType1 $ob1)
{
// Exception Handling code for Exception Type 1
}
catch (ExceptionType2 $ob2)
{
// Exception Handling code for Exception Type 2
}
…………………
…………………
catch (ExceptionTypeN $obN)
{
// Exception Handling code for Exception Type N
}

The detail description of each block is given below:
(1) Try: The code to be executed or code that may cause an exception condition is put in the try block. If any exception conditions arise in the try block then new object of type exception is automatically created and throw by the try block.
(2) Catch: The exception object that is thrown from Try block is caught by the catch block. The single try block can have one or multiple catch blocks.
(3) Throw: The system generated exceptions are automatically thrown by the system from the try block. But if you want to manually generate any exception object then you can use throw keyword.
Consider Following Example:

In the above example we are trying to divide Number1 by Number2. The code is written inside try block. First we check weather Number2 is 0 or not. If it is 0 then we are throwing an exception object from the try block.
The object that is thrown from the try block is caught in the catch block which display the error message as shown below:

Download Projects


Download Programs