PHP code for Exception

Try block throws Exception if occured.

Exception can be caught and handled by Catch Block.

A Code is always executed in finally block.

Example :

<?php
//code by aryatechno
class Aryatechno extends Exception {

function learn($dividend, $divisor){
try {
// code to be executed.
// Try block throws Exception if occured.
echo "</br>Inside try block";


if ($divisor == 0) {
throw new Exception("Divide by Zero");
}else
{
$num= $dividend/$divisor;
}
echo "</br>Code after exception can not be executed.";
}catch(Exception $e) {
// Exception can be caught and handled by Catch Block.
echo "</br> Exception Error : ".$e->getMessage();
}catch(InvalidArgumentException $e) {
//multiple catch blocks within try catch
echo "</br>Invalid Argument Exception : ".$e->getMessage();
}finally {
echo "</br> This Code is always executed in finally block!";
}
}
}

$obj = new Aryatechno;
$obj->learn(12,6);
$obj->learn(14,0);
?>

Output :

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

50062