PHP  Exception Handling


 

PHP  Exception Handling

PHP  Exception Handling tutorial gives an overview of exception handling technique of PHP, it includes few example of Exception handling Class, which helps you to understand in better way.

PHP  Exception Handling tutorial gives an overview of exception handling technique of PHP, it includes few example of Exception handling Class, which helps you to understand in better way.

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)

{

0

echo"After throwing exception from catch block we are inside the myNumber funtion";

throw new Exception("Value of $a is greater than $b");

}

1

}

//trigger exception inside the try block

try

2

{

echo "Inside the try block <br/>";

3

myNumber(22,2);

}

//catch the exception inside the catch block

4

catch(Exception $e)

{

5

echo"Inside the catch block <br/>";

echo $e->getMessage();

}

6

?>

Output of 2nd example: 

7

Inside the try block
Inside the catch block
Value of 22 is greater than 2

 

 

8

PHP Exception Handling Example -3

<?php

 

9

try

{

0

echo (div(3))."<br/>";

echo (div(4))."<br/>";

echo (div(0));

1

}

catch(Exception $e)

2

{

echo $e->getMessage();

}

3

 

function div($x)

4

{

if (! $x)

{

5

throw new Exception('Division by zero');

}

else

6

return 1/$x;

}

 

7

?>

Output of Example 3:

8

0.33333333333333
0.25
Division by zero

Ads