saftutorials.com
PHP EXCEPTION Tutorial

PHP 5 has an exception model similar to another programming languages. It is used to change the normal flow of program execution if a specified error occurs.This is called an exception.

There are three new keywords related to exception

Try - A function using an exception should be in a "try" block. If the exception does not trigger,

the code will execute as normal execution. However if the exception triggers, an exception is "thrown".


Throw - This is how you trigger an exception. Each "throw" must have at least one "catch" block.


Catch - A "catch" block retrieves an exception and creates an object containing the exception information.

Let's try an example with Try, Throw and Catch

<?php
//create a function with an exception
function checkIntegerOrNot($variable) {
if(filter_var($variable, FILTER_VALIDATE_INT) === FALSE) {
throw new Exception("Value must be an integer");
}
return true;
}
//trigger exception in a "try" block
try {
checkIntegerOrNot('testing');
//If the exception is thrown, this text will not be shown
$message = 'If you see this, the number is an integer';
}
//catch exception
catch(Exception $e) {
$message = $e->getMessage();
}
?>
<!DOCTYPE html>
<html>
<body>
<h1>Error Handling by using try, throw and catch</h1>
<?php
if($message) {
echo "Message : ".$message;
}
?>
</body>
</html>

The above code produces the following results

Message: Value must be an integer


If we pass the integer value as parameter of checkIntegerOrNot() function then result would be

Message: If you see this, the number is an integer



Find us on

Facebook Google Plus Twitter Pinterest YouTube

web statistic