Exceptions Handling In PHP

PHP 5 has an exception model similar to other programming languages. Exceptions are important and provide better control over error handling. The main purpose of using exception handling is to maintain the normal execution of the application.

Why Exception handling?

1. In a perfect world, your program is like driving a bike on test track.
2. In real world, programming remains as an ideal dream.
3. Unforeseen events, that disrupt the normal flow may occur.
4. In programming world, these events are known as exceptions.
5. During runtime, if any error occurs, an object with the error information is created.This object is called exception object.
6. Providing this object to the run time system is called as exception handling.
7. When an exception occurs, execution will switch to the exception handler?

Exception Keywords

PHP offers the following keywords for this purpose:

try - The try block contains the code that may have an exception or where an exception can arise. When an exception occurs inside the try block during runtime of code, it is caught and resolved in catch block. The try block must be followed by catch or finally block. A try block can be followed by minimum one and maximum any number of catch blocks.
throw - This is how you trigger an exception. Each "throw" must have at least one "catch".
catch - A "catch" block retrieves an exception and creates an object containing the exception information

Exception Handling Methods

Method Description
getMessage() : Returns the message passed to the constructor
getCode() : Returns the error code passed to the constructor
getLine() : Returns the line number where the exception was thrown
getFile() : Returns the name of the file which has thrown the exception
getTrace() : Returns the array which consists the information like file name, line, function and its parameters
getTraceAsString(): Returns the information given by getTrace() in string format

Example

try{
    $FH=fopen("input.txt","r");
    if(!$FH){
 throw new Exception("no input file",1);   
}
    $SH=fopen("config.txt","r");
    if(!$SH){
        throw new Exception("no config file",2);
    }
    echo  "File are opened successfully";
}
catch (Exception $e){
    echo "Error:".$e->getMessage()."
"; echo "Code:".$e->getCode()."
"; }