PHP Exception Handling
PHP 5 has included a new way of error handling - Exception handling, which is present in other OOP based programming language.
In PHP there are three blocks in Exception Handling : try, catch, and throw.
i) Try: The try block should have a function which is used to handle the exception.
ii) Throw: This block is used to trigger an exception. Each throw must have at least one.
iii) Catch:- This block is used to retrieve an exception and instantiates an object, which contains the exception message.
Code for PHP Exception Handling:
PHP Exception Handling Example - 1
<?php
try {
throw new Exception("Some error message");
} catch(Exception $e) {
echo "The exception occured at line: " . $e->getLine();
}
?>
Output of example 1st Example:
The exception occurred at line: 3
PHP Exception Handling Example - 2
<?php //create function with an exception
function myNumber($a,$b)
{
if ($a > $b)
{
echo"After throwing exception from catch block we are inside the myNumber funtion";
throw new Exception("Value of $a is greater than $b");
}
}
//trigger exception inside the try block try
{
echo "Inside the try block <br/>";
myNumber(22,2);
}
//catch the exception inside the catch block
catch(Exception $e)
{
echo"Inside the catch block <br/>";
echo $e->getMessage();
}
?>
Output of 2nd example:
Inside the try block
Inside the catch block
Value of 22 is greater than 2
PHP Exception Handling Example -3
<?php try
{
echo (div(3))."<br/>";
echo (div(4))."<br/>";
echo (div(0));
}
catch(Exception $e)
{
echo $e->getMessage();
}
function div($x)
{
if (! $x)
{
throw new Exception('Division by zero');
}
else
return 1/$x;
}
?>
Output of Example 3:
0.33333333333333
0.25
Division by zero