Q:

PHP program to demonstrate the NULL reference exception using exception handling

0

Here, we will use trycatch, and throw keywords to demonstrate the NULL reference exception in a PHP program.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to demonstrate the NULL reference exception using exception handling is given below. The given program is compiled and executed successfully.

<?php
//PHP program to demonstrate the NULL reference exception
//using exception handling.
class Sample
{
    public function PrintHello()
    {
        printf("Hello World<br>");
    }
}

function GetObject()
{
    $obj = new Sample();
    return $Obj;
}
try
{
    $obj = GetObject();

    if ($obj == null) throw new Exception("Null reference exception");

    $obj->PrintHello();
}
catch(Exception $e)
{
    printf("Exception: %s", $e->getMessage());
}
?>

Output:

Exception: Null reference exception

Explanation:

Here, we created used try and catch block. In the try block we created a class Sample that contains a method PrintHello(), which is used to print "Hello World" on the webpage.

Here, we created a function GetObject(), which is used to return the object of Sample class, here we created object $obj of Sample class but we return $Obj. That's why it will return a null value.

if($obj==null)
    throw new Exception("Null reference exception");

Here, we check the value of $obj, if it contains a null value then Exception will be thrown an caught by the catch block and print the specified exception message on the webpage.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now