Sarah
Sarah

Reputation: 2003

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

I have a method that saves contact information to a database. In the method I want to return true if it is successfully saved and then return false if not.. I am using a try catch block though. can I return false instead of throwing the exception? it works like this but I'm just wondering is it good practice because it is for a college assignment. thanks

In my contact_functions.php page:

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;
    }
}

then in my contact_handler.php page:

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

Upvotes: 3

Views: 11026

Answers (2)

Tejaswi Sharma
Tejaswi Sharma

Reputation: 158

Exception should be thrown when there is no way your code can proceed further. returning true and false is a feedback to your code users. If you want to return false when you get exception its entirely your choice and totally possible

Upvotes: 2

Kuba Birecki
Kuba Birecki

Reputation: 3016

Exceptions should be thrown when a function/method fails to follow it's natural behaviour.

In your case, the function returns a status indicating whether the insert succeeded or failed. Therefor it makes perfect sense to handle any exceptions associated with the database operation inside that function, as you have done.

On the other hand, if you were fetching data, and the function was supposed to return that data, it would be correct to throw an exception when it fails, instead of returning 'something different'.

Anyhow, if you throw an exception, you should eventually handle it.

Upvotes: 6

Related Questions