PHP Tutorial

PHP Examples

PHP Practice

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 [Last updated : March 13, 2023]

Creating a User-Defined Exception Class

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

PHP code to create a user-defined exception class

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 »





Comments and Discussions!

Load comments ↻





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