Everything You Need To Know About Exception Handling In PHP

Posted by TotalDC

We are continuing our PHP tutorial series and in this tutorial let’s talk about exception handling in PHP.

What Is An Exception In PHP

An exception is a signal that lets you know that some kind of event or error has occurred.

Exceptions can appear due to various reasons, let’s say if your database connection fails the file that you are trying to access doesn’t exist, etc.

PHP has a powerful exception-handling mechanism that allows you to handle exceptions with ease. In other words, exception handling is the object-oriented method for handling errors, which provides a more flexible form of error reporting. The exception model was first introduced in PHP 5.

How To Use Throw and Try…Catch Statements In PHP

In this approach program code is written in a try block, an exception can be thrown using the throw statement when an event occurs during the execution of code in a try block. It is then caught and resolved by one or more catch blocks.

Here is a demonstration of how exception handling works:

function division($dividend, $divisor){
    // Throw exception if divisor is zero
    if($divisor == 0){
        throw new Exception('Division by zero.');
    } else{
        $quotient = $dividend / $divisor;
        print "<p>$dividend / $divisor = $quotient</p>";
    division(10, 2);
    division(30, -4);
    division(15, 0);
    // If exception is thrown following line won't execute
    print '<p>All divisions performed successfully.</p>';
} catch(Exception $e){
    // Handle the exception
    print "<p>Caught exception: " . $e->getMessage() . "</p>";
// Continue execution
print "<p>Hello World!</p>";

The exception handling system in PHP has four parts: try, throw, catch, and exception class. Let’s look at how exactly each part works:

  • The division() function in the example checks if a divisor is equal to zero. If it is, an exception is thrown using PHP’s throw statement. Otherwise, this function performs the division using given numbers and displays the result.
  • Then the division() function is called within a try block with different arguments. If an exception is generated while executing the code within the try block, PHP stops execution and attempts to find the corresponding catch block. If it is found, the code in the catch block is executed, if not, a fatal error is generated.
  • The catch block typically catches the exception thrown within the try block and creates an object ($e) containing the exception information. The error message from this object can be retrieved using the Exception’s getMessage() method.

PHP exception class also has getCode(), getFile(), getLIne(), and getTraceAsString() methods that can be used to generate detailed debugging information.

// Turn off default error reporting
    $file = "somefile.txt";
    // Attempt to open the file
    $handle = fopen($file, "r");
        throw new Exception("File cannot be opened!", 5);
    // Attempt to read the file contents
    $content = fread($handle, filesize($file));
        throw new Exception("File cannot be read!", 10);
    // Closing the file handle
    // Display file contents
    print $content;
} catch(Exception $e){
    print "<h3>Caught Exception!</h3>";
    print "<p>Error message: " . $e->getMessage() . "</p>";    
    print "<p>File: " . $e->getFile() . "</p>";
    print "<p>Line: " . $e->getLine() . "</p>";
    print "<p>Error code: " . $e->getCode() . "</p>";
    print "<p>Trace: " . $e->getTraceAsString() . "</p>";

The exception’s constructor can take an exception message and exception code. While the exception message is used to display generic information about what is wrong with your code, the exception code can be used to categorize the errors. The exception code provided can be retrieved later using getCode() method.

How To Define Custom Exceptions In PHP

You can define your custom exception handlers for different types of exceptions. It allows you to use a separate catch block for each exception type.

You can define a custom exception by extending the exception class because it is the base class for all exceptions. The custom exception class inherits all the properties and methods from PHP’s exception class. You can add your custom methods to the custom exception class. Here’s an example:

// Extending the Exception class
class EmptyEmailException extends Exception {}
class InvalidEmailException extends Exception {}
$email = "user@yourwebsite.com";
    // Throw exception if email is empty
    if($email == ""){
        throw new EmptyEmailException("<p>Enter your E-mail address</p>");
    // Throw exception if email is not valid
    if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {           
        throw new InvalidEmailException("<p><b>$email</b> is not a valid E-mail address!</p>");
    // Display success message if email is valid
    print "<p>SUCCESS: Email validation successful.</p>";
} catch(EmptyEmailException $e){
    print $e->getMessage();
} catch(InvalidEmailException $e){
    print $e->getMessage();

In this example, we have derived two new exception classes – EmptyEmailException and InvalidEmailException from the exception base class. As you can see, multiple catch blocks are used to display different error messages, depending on the type of exception generated.

These custom exception classes inherit the properties and methods from the exception class, so you can use the exception class methods like getMessage(), getLine(), getFile(), and more to retrieve error information from the exception object.

How To Set Global Exception Handler In PHP

If an exception is not caught, PHP generates a fatal error with an “Uncaught Exception…” message. This error message can contain sensitive information for example file name and line number where the problem occurs. If you don’t want to expose this info to the user you can create a custom function and register it with the set_exception_handler() function to handle all uncaught exceptions. Here’s an example:

function handleUncaughtException($e){
    // Display generic error message to the user
    print "Something went wrong. Please try again.";
    // Construct the error string
    $error = "Uncaught Exception: " . $message = date("Y-m-d H:i:s - ");
    $error .= $e->getMessage() . " in file " . $e->getFile() . " on line " . $e->getLine() . "\n";
    // Log details of error in a file
    error_log($error, 3, "var/log/exceptionLog.log");
// Register custom exception handler
// Throw an exception
throw new Exception("Testing Exception");