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!