ADVERTISEMENT
ADVERTISEMENT

PHP program to create a user-defined exception class

Here, we are going to learn how to create a user-defined exception class in PHP?
Submitted by Nidhi, on November 22, 2020

Here, we will create a user-defined class that inherits the Exception class and then we will throw an exception using the throw keyword.

Program/Source Code:

The source code to create a user-defined exception class is given below. The given program is compiled and executed successfully.

<?php
// PHP program to demonstrate the user-defined exception.
class UserException extends Exception
{
}

try
{
    $exp = new UserException("User defined exception");
    throw $exp;
}
catch(UserException $e)
{
    printf("Exception: %s", $e->getMessage());
}
?>

Output:

Exception: User defined exception

Explanation:

Here, we created a class UserException by inheriting a predefined class Exception.

try 
{  
    $exp = new UserException("User defined exception"); 
    throw $exp;
}  

Here, we created the object of UserException class and throw an exception using throw that will be caught by the catch block and print a specified 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.