How can exceptions be utilized in PHP to handle logging and debugging instead of relying on magic constants like __FILE__ and __LINE__?

When handling exceptions in PHP, you can create a custom exception class that extends the built-in Exception class. Within this custom exception class, you can include methods to log the exception details, such as the file and line where the exception occurred. By utilizing this custom exception class, you can have more control over how exceptions are logged and debugged without relying on magic constants like __FILE__ and __LINE__.

class CustomException extends Exception {
    public function logException() {
        $message = "Exception: " . $this->getMessage() . " in " . $this->getFile() . " on line " . $this->getLine();
        error_log($message);
    }
}

try {
    // Code that may throw an exception
    throw new CustomException("An error occurred.");
} catch (CustomException $e) {
    $e->logException();
}