我可以从 try 和 catch 返回 false 而不是抛出异常吗

Sar*_*rah 3 php return try-catch

我有一种将联系信息保存到数据库的方法。在该方法中,如果成功保存,我想返回 true,如果没有成功保存,则返回 false。不过,我使用的是 try catch 块。我可以返回 false 而不是抛出异常吗?它的工作原理是这样的,但我只是想知道这是一个好的做法,因为它是针对大学作业的。谢谢

在我的contact_functions.php页面中:

function saveContactInfo($firstName, $lastName, $email, $subject, $message, $pdoConnection){
    //Get timestamp of current time and store it into a variable
    //This is so we can keep a record of the time a message was sent.
    $messageTime = time(); 

    try{
        $query ="INSERT INTO contact_info (firstName, lastName, email, subject, message, messageTime) VALUES (:firstName, :lastName, :email, :subject, :message, :messageTime)";
        $statement = $pdoConnection->prepare($query);
        //bind our values. they will all be srting parameters.
        $statement->bindValue(':firstName', $firstName, PDO::PARAM_STR); 
        $statement->bindValue(':lastName', $lastName, PDO::PARAM_STR); 
        $statement->bindValue(':email', $email, PDO::PARAM_STR); 
        $statement->bindValue(':subject', $subject, PDO::PARAM_STR);
        $statement->bindValue(':message', $message, PDO::PARAM_STR); 
        $statement->bindValue(':messageTime', $messageTime, PDO::PARAM_STR); 
        $statement->execute();
        return true;
    }catch(PDOException $e){
        //throw new pdoDbException($e); 
        //return "Error message " . $e->getMessage();
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在我的contact_handler.php页面中:

if (saveContactInfo($firstName, $lastName, $email, $subject, $message, $pdoConnection)) {
        echo 'Your Message has been sent!!';    
    } else {
        echo 'There was a problem with your message!!'; 
    }
Run Code Online (Sandbox Code Playgroud)

Kub*_*cki 6

当函数/方法未能遵循其自然行为时,应抛出异常。

在您的情况下,该函数返回一个状态,指示插入是成功还是失败。因此,像您所做的那样,处理与该函数内的数据库操作相关的任何异常是非常有意义的。

另一方面,如果您正在获取数据,并且该函数应该返回该数据,那么在失败时抛出异常是正确的,而不是返回“不同的东西”。

无论如何,如果你抛出异常,你最终应该处理它。