What are Exceptions and RuntimeExceptions in PHP?

In PHP, Exception handling is a process used to manage errors in a controlled fashion. It was introduced in PHP 5 and it has become a standard practice for handling errors in more modern PHP code.

An Exception in PHP is a standard class that can be used to signal that an error has occurred. When an exception is “thrown,” it represents an unusual or exceptional condition that has occurred in the code. It’s sort of like an SOS signal that can be caught and handled with special code known as a “catch” block.

RuntimeException

throw new RuntimeException();

RuntimeException is a type of exception that represents errors which can only be detected during runtime. For example, this could include errors such as trying to access an array element that doesn’t exist, or maybe failing to open a non-existent file. RuntimeException is a subclass of Exception, which is more general.

Exception

throw new Exception();

Exception is the base class for all exceptions in PHP. When you throw an Exception, you’re signaling that there’s a general error condition that you want to handle.

Both of these are followed by the throw keyword, which in PHP signals that an exception is being thrown.

What catches these thrown exceptions?

To catch an exception, you must wrap your code with a try block, and immediately follow it with one or more catch blocks. Here is a simple example:

try { // Code that may throw an exception 
    if ( some_bad_condition() ) { 
        throw new Exception( "Something went wrong" ); 
    } 
} catch ( Exception $e ) { 
    // Handle exception 
    echo "Error: " . $e->getMessage(); 
}

How it works:

  • The try Block: You enclose the code that might throw an exception within a try block. If no exception is thrown, the code continues normally and any catch blocks are skipped.
  • The throw Statement: Within a try block, if a condition arises that you cannot handle, you “throw” an exception. You can pass a message to the exception’s constructor, which can then be used later in the catch block.
  • The catch Block: If an exception is thrown inside the try block, execution stops immediately and jumps directly to the catch block, if there is one that matches the type of the exception thrown. The catch block can then access information about the exception through the caught exception object.

A script can have multiple catch blocks to handle different types of exceptions in different ways:

try { 
    // Code that may throw different types of exceptions 
} catch ( RuntimeException $e ) { 
    // Handle runtime exceptions specifically 
} catch ( Exception $e ) { 
    // Handle all other exceptions 
}

Real-world Example:

Here’s an example from some real code I’m writing. See how I’m using the two different types of exceptions.

private function get_settings(): stdClass {
    $response = wp_remote_get(
        'https://examplewebsite.com/wp-json/custom-plugin/v1/settings/'
        array( 'Accept' => 'application/json' )
    );
    if ( is_wp_error( $response ) ) {
        throw new RuntimeException( $response->get_error_message(), $response->get_error_code() );
    }

    $response_code = wp_remote_retrieve_response_code( $response );
    $response_body = wp_remote_retrieve_body( $response );
 
    // Check that the response code is a 2xx code.
    if ( ! \str_starts_with( (string) $response_code, '2' ) ) {
        $response_message = wp_remote_retrieve_response_message( $response );
        throw new Exception( $response_message, $response_code );
    }

    // Parse the response body as JSON.
    return json_decode( $response_body, false, 512, JSON_THROW_ON_ERROR );
}

public function init(): void {
    try {
        $this->settings = $this->get_settings();
    } catch ( Exception $exception ) {
        // Optionally error log, output as an admin notice, etc. 
    }
   
     // Continue with plugin initialization.
}

Exception handling is a powerful tool that makes your code more robust and easier to debug since it separates error handling code from the rest of your code logic.

PHP Manual on Exceptions:  https://www.php.net/manual/en/language.exceptions.php