Execution sequence of try. catch and return in PHP

Source: Internet
Author: User
Execution sequence of try. catch and return in PHP
try {      $pdo->begintransaction();      foreach ($sql_arr as $sql) {            $stmt = $pdo->exec($sql);      }      $pdo->commit();      return true;} catch (Exception $e) {      echo $e->getMessage();      $pdo->rollBack();      return false;}


As shown above. Please help me explain the execution order of the return statements in the try catch statement in php?
In the above code, we want to return true if the pdo operation is normal. if an exception occurs, false is returned. can this problem be implemented properly?


Reply to discussion (solution)

In this case, true is returned for normal operation. if an exception occurs, false is returned.

However, you must set the property item PDO: ATTR_ERRMODE to PDO: ERRMODE_EXCEPTION.
Otherwise, the exception handling is invalid.

And
Exception $ e
To write
PDOException $ e

There are still many problems

The moderator has already answered this question. here is a small example of mixed score.

$ Res = test ('oo '); if ($ res) {echo 'heha';} function test ($ name) {try {a ($ name ); return true;} catch (Exception $ e) {echo $ e-> getMessage (); return false ;}} function a ($ name) {if ($ name = "xx") {return true;} else {throw new Exception ("error ");}}

In this case, true is returned for normal operation. if an exception occurs, false is returned.

However, you must set the property item PDO: ATTR_ERRMODE to PDO: ERRMODE_EXCEPTION.
Otherwise, the exception handling is invalid.

And
Exception $ e
To write
PDOException $ e

There are still many problems


Thank you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.