Wie können Exceptions in PHP verwendet werden, um auf Sicherheitsverletzungen oder unerlaubte Aktionen in Klassenmethoden angemessen zu reagieren?

Exceptions in PHP can be used to handle security violations or unauthorized actions in class methods by throwing an exception when such violations occur. This allows for a controlled and structured way to handle errors and prevent unauthorized access to certain functionalities within the class.

class SecureClass {
    public function sensitiveOperation() {
        if (!userIsAuthorized()) {
            throw new Exception("Unauthorized access");
        }
        // Perform sensitive operation
    }
}

try {
    $secureObj = new SecureClass();
    $secureObj->sensitiveOperation();
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}