How can PHP developers ensure that their custom exception classes are properly implemented and avoid common errors, such as accessing empty properties?
When implementing custom exception classes in PHP, developers should ensure that they properly initialize any properties within the class to avoid accessing empty properties. This can be achieved by setting default values or checking if the property is set before accessing it within the class methods.
class CustomException extends Exception {
protected $customMessage;
public function __construct($message = "", $code = 0, Throwable $previous = null) {
$this->customMessage = $message;
parent::__construct($message, $code, $previous);
}
public function getCustomMessage() {
return isset($this->customMessage) ? $this->customMessage : '';
}
}
// Example usage
try {
throw new CustomException("Custom exception message");
} catch (CustomException $e) {
echo $e->getCustomMessage();
}