PHP - Custom Exception Classes

Creating custom exception classes in advanced PHP allows you to handle specific error scenarios with more detail and clarity. Custom exceptions help differentiate between various types of errors and provide informative error messages. Here's how you can create and use custom exception classes:

Defining Custom Exception Classes:

To create a custom exception class, you need to extend the built-in Exception class or any of its subclasses. You can add additional properties or methods to your custom exception class to provide more context about the error.

class CustomException extends Exception {
  public function __construct($message = "", $code = 0, Throwable $previous = null) {
      parent::__construct("Custom: " . $message, $code, $previous);
  }
  // Additional methods and properties can be added here
}

Throwing Custom Exceptions:

You can throw instances of your custom exception class using the throw statement. Provide an instance of your custom exception class along with a descriptive error message.

function processUserData($data) {

  if (empty($data)) {
      throw new CustomException("User data cannot be empty.");
  }
  // Process user data
}

Catching Custom Exceptions:

To catch custom exceptions, use try and catch blocks just like you would with built-in exceptions. Place a catch block for your custom exception type after the try block.

try {
  processUserData([]);
} catch (CustomException $e) {
  echo "Custom Exception Caught: " . $e->getMessage();
} catch (Exception $e) {
  echo "Other Exception Caught: " . $e->getMessage();
}

The catch block for CustomException handles exceptions of your custom type, while the Exception catch block handles any other exceptions.

Adding Context to Custom Exceptions:

You can include additional context in your custom exceptions by adding methods or properties. For instance, you might include data related to the error, such as invalid user input.

class ValidationException extends Exception {
  private $invalidFields;
  public function __construct($message = "", $invalidFields = [], $code = 0, Throwable $previous = null) {
      parent::__construct($message, $code, $previous);
      $this->invalidFields = $invalidFields;
  }
  public function getInvalidFields() {
      return $this->invalidFields;
  }
}
// Throwing and catching the custom exception
try {
  $invalidFields = ['username', 'email'];
  throw new ValidationException("Validation failed.", $invalidFields);
} catch (ValidationException $e) {
  echo "Validation Exception: " . $e->getMessage();
  echo "Invalid Fields: " . implode(', ', $e->getInvalidFields());
}

Custom exception classes enable you to create a more structured and meaningful way of handling errors. By providing detailed error messages and additional contextual information, you can improve debugging and troubleshooting processes in your PHP application.