Open In App

How to throw an Exception in PHP?

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

In PHP, you can throw exceptions to indicate that an error or exceptional condition has occurred during script execution. This allows you to gracefully handle errors by interrupting the normal flow of the program and providing a mechanism for error propagation.

To throw an exception in PHP, you use the throw keyword followed by an object that represents the exception being thrown. Typically, you’ll use instances of the built-in Exception class or its subclasses to represent different types of exceptions.

Syntax:

throw new Exception("An error occurred");

In this example, we’re throwing a generic Exception with the message “An error occurred”. However, you can also create custom exception classes that extend the Exception class to represent specific types of errors:

class CustomException extends Exception {
// Custom properties or methods can be defined here
}

// Throwing a custom exception
throw new CustomException("Custom error message");

Using try-catch block

When an exception is thrown, the normal execution flow is interrupted, and PHP will search for the nearest catch block that can handle the exception. If no suitable catch block is found, PHP will terminate the script and display an uncaught exception error message.

try {
// Code that may throw an exception
throw new Exception("An error occurred");
} catch (Exception $e) {
// Handling the exception
echo "Exception caught: " . $e->getMessage();
}

In this example, the catch block catches the exception thrown within the try block and handles it by printing out the error message. You can include additional logic within the catch block to handle exceptions as needed, such as logging errors or displaying user-friendly error messages.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads