Open In App

How to use the Exception Class in PHP ?

In PHP, the Exception class is a built-in class used for representing exceptions, which are a mechanism for handling errors or exceptional conditions during script execution. When an error occurs that disrupts the normal flow of execution, an exception can be thrown, and the Exception class is used to encapsulate information about the error, such as an error message, code, and stack trace.

Syntax:

// Throwing an exception
throw new Exception("Error message");

// Catching and handling an exception
try {

// Code that may throw an exception
} catch (Exception $e) {

// Handle the exception
echo "Exception caught: " . $e->getMessage();
}

Usage:

Article Tags :