php throw exception stop execution - php

I have this code:
function divide($a,$b){
try{
if($b==0){
throw new Exception("second variable can not be 0");
}
return $a/$b;
}
catch(Exception $e){
echo $e->getMessage();
}
}
echo divide(20,0);
echo "done";
It throws an exception when the second parameter is 0. How can I stop done from printing?

Don't catch your exception in divide() and catch it later:
function divide($a,$b){
if($b==0){
throw new Exception("second variable can not be 0");
}
return $a/$b;
}
try {
echo divide(20,0);
echo "done";
} catch(Exception $e){
echo $e->getMessage();
}

Related

PHP rollback method has failed

I have tried this piece of code and unfortunately rollback method failed!
Thank in advance!!
$bash = new mysqli('localhost', 'root', '','dbastegoi');
$bash->autocommit(FALSE);
echo 'timologio';
$r =$bash->query("INSERT INTO tbparastatika (strArithmos, fkERGO, strPROMITH, sngCOST, intTYPOS, intDRASH) VALUES ('1','1001','123123123',800138,1,1)");
//ΕΙΣΑΓΩΓΗ ΤΙΜΟΛΟΓΙΟΥ
$i = $bash->insert_id;
ECHO PHP_EOL;
echo 'dapanh';
try {
$r =$bash->query("INSERT INTO tbdapanes_stegash (idPARASTATnIKO, sngCOST, fkDIAMERISMA, intMONTH) VALUES ($i,100,1,1)");
echo $r;
} catch (Exception $e) {
echo 'error2';
}
$bash->commit();
$bash->rollback();
//$SYNDESH->commit();
//$SYNDESH->rollback();
$bash->close();
You can not make a commit first and then a roolback. You have to make a commit if your query runs without error or make a rollback if you get an error:
try {
$r =$bash->query("INSERT INTO tbdapanes_stegash (idPARASTATnIKO, sngCOST, fkDIAMERISMA, intMONTH) VALUES ($i,100,1,1)");
echo $r;
$bash->commit();
} catch (Exception $e) {
echo 'error2';
$bash->rollback();
}

error class not catching thrown errors

I have an exception class that looks like this
<?php
class Errors{
public function displayError(Exception $e){
$trace = $e->getTrace();
if($trace[0]['class'] != ""){
$class = $trace[0]['class'];
$method = $trace[0]['function'];
$file = $trace[0]['file'];
$line = $trace[0]['line'];
$error_message = $e->getMessage().
"<br /> Class/Method : ".$class." <==> ".$method.
"<br /> File : ".$file.
"<br /> Line : ".$line;
}
return $error_message;
}
}
?>
This works fine for many errors that are thrown due do typos/column count not matching value count, but when I throw an exception from the code myself, I get an error. For example
try{
$stmt = $db->dbh->prepare("SELECT user FROM reset ");
$stmt->execute();
if ($stmt->rowCount() < 1){
throw new Exception('The Link expired, request a new one');
} else {
throw new Exception('The Link is invalid, please request a new one');
}
}
catch (PDOException $e) {
$error = new Errors();
echo "<b>".$error->displayError($e)."</b>";
}
I get Uncaught exception 'Exception' with message 'The Link is invalid, please request a new one' error when I run the code. If I remove that line, and induce an error by spelling SELECT as SLECT, the error class works fine.
How can I make in such a way that the error class will catch all types of errors ?
The problem is NOT all exceptions are PDOExceptions.You code cacthes only PDOException which means new Exception won't be catched. Try :
try
{
$stmt = $db->dbh->prepare("SELECT user FROM reset ");
...
}
catch (PDOException $e)
{
$error = new Errors();
echo "<b>".$error->displayError($e)."</b>";
}
catch (Exception $e)
{
$error = new Errors();
echo "<b>".$error->displayError($e)."</b>";
}
The reason why your code works when you spell SELECT as SLECT is because you triggered a PDOException instead of a new Exception.

Yii how to check if query execution failed

I M Using YII to develop web application
i want to check if query executed successfully or not
$data = Yii::app()->db->createCommand($SQL);
$result = $data->queryAll();
if(count($result) == 0)
{
throw new SoapFault('Sender', 'Unable to get display information.');
}
if code will execute if select query return no result-set. but i want to check if query executed successfully or not. based on that i want to throw exception. then if query executed successfully and returned no result-set then some other exception.
how to do this ? any suggestions ?
try {
$result = $data->queryAll();
} catch (Exception $ex) {
echo 'Query failed', $ex->getMessage();
}
try
{
$result = Yii::app()->db->createCommand($sqlQuery)->execute();
echo 'success';
}
catch (Exception $e)
{
echo 'fail';
}

try catch issue with deadlock

i use below code -Just try again. - to prevent deadlock.
it seems when code goes to catch part query2 run before query1.
and i see this output "query2 run before query 1";
is it true?
try
{
$query1="....";
}
catch
{
$query1="....";//repeat query1 in try
$t1=microtime();
}
$query2="....";
$t2=microtime();
if ($t2<$t1)
{
echo "query2 run before query 1";
}
No it's not true
echo '1';
try {
echo '2';
throw new Exception;
} catch (Exception $e) {
echo '3';
}
echo '4';
// Prints 1234

detect exception - if

If i have this:
function valid($valor) {
foreach($valor as $valor){
if (!empty($valor)) {
if (preg_match("/[^A-Za-z0-9-áàçéúâôóã ]|(\d+)/", $valor)) {
$error = "invalid";
throw new Exception($error);
}
}
}
}
and
if (isset($_POST['myform'])){
if ($val_->valid($form1['new'])) {
echo "ok";
}
else
echo "bad";
}
but i got: Fatal error: Uncaught exception 'Exception
What i want is basically something like that (pseudo code):
if (exception true) {
echo "problem";
}
else
echo "ok";
How can i do that ?
You have to handle the exception.
try {
...
//statements
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
EDIT:
try{
if ($val_->valid($form1['new'])) {
echo "ok";
}
}catch(Exception $e){
echo "bad";
}

Categories