PHP Tutorial

PHP Examples

PHP Practice

PHP program to demonstrate the NULL reference exception using exception handling

Here, we are going to demonstrate the NULL reference exception using exception handling in PHP.
Submitted by Nidhi, on November 22, 2020 [Last updated : March 13, 2023]

Handing NULL Reference Exception

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

PHP code to handle NULL reference exception

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.

PHP Exception Handling Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.