我可以从尝试和捕获返回false而不是抛出异常吗


Can I return false from a try and catch instead of throwing exception

我有一个方法可以将联系人信息保存到数据库中。在方法中,如果成功保存,我希望返回true,如果不成功,则返回false。。不过我用的是一个尝试接球的盖帽。我可以返回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;
    }
}

然后在我的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!!'; 
    }

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

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

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

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

当代码无法继续执行时,应抛出异常。返回true和false是对代码用户的反馈。如果你想在得到异常时返回false,这完全是你的选择,也是完全可能的