Open In App

How to use the Exception Class in PHP ?

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Error Representation: The Exception the class encapsulates information about errors or exceptional conditions, such as error messages, codes, and stack traces.
  • Exception Handling: Exceptions thrown during script execution are caught and handled using try-catch blocks, providing a mechanism for error recovery and alternative execution paths.
  • Customization: Developers can extend the Exception class to create custom exception types tailored to specific error scenarios, allowing for more granular error handling.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads