ADVERTISEMENT
ADVERTISEMENT

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

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

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.

PHP Exception Handling Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.