Tuesday, April 2, 2013

OOP -> Exception

Exception Handling is used to handle the error. It can handle all types of error like Warning, Notice, User defined Error message etc but unfortunately it can not handle fatal error.

We can also suppress the error with the use of  "@"  error operator. But we use exception handling so that we can show the readable error message to users.

Following are the example of exception handling.

function inverse($x) {
    if (!$x) {
        throw new Exception('Can not Division by zero.');
    }
    else return 1/$x;
}

try {
    echo inverse(50) . "\n";
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}


Try: set the statements which you want to test.
catch: If error comes, statement fall under catch

No comments:

Post a Comment