I have a try block in which some exceptions will be definitely thrown but I don't want to stop the execution of the try block if this happens.
This is the code:
try {
$queryStr = "SELECT * FROM `$current_table` WHERE ...";
$query = $db->prepare($queryStr);
$query->execute();
while($row = $query->fetch()) {
}
} catch(PDOException $e) {
//echo $e->getMessage();
}
This try/catch block is inside a for loop, so $current_table
will be changing continously. Now this current table can take 4 values april-june-2014
, july-september-2014
, october-december-2014
and jan-march-2015
. These table names are stored in an array.
Now when it will query the first table and if it is found, then it's well and good but if it is not found then I want to check the other tables and see if those exists. If any of the table is not found, it will throw an exception and then it won't check the other tables.
Is there a way to do that?
I actually had some structure problems in tables so because of that I was unable to get data from them. But this code is working fine. The remaining code in try block will be executed even if there is an exception. So there is no need to add anything else.
You can put your code that must execute irrespective of exception, into a finally
block. Check this
Use a continue statement:
for (/* condition */) {
try {
// things
} catch (Exception $e) {
continue;
}
// won't reach here if exception was caught
}
Example (try this out on WriteCodeOnline):
$counter = 0;
for ($i = 0; $i < 5; $i++) {
try {
$counter++;
if ($counter != 3) {
throw new Exception("Test");
}
} catch (Exception $e) {
continue;
}
echo "This only prints when an exception is not thrown (when \$counter is 3). See: \$counter = " . $counter;
}
echo "
";
var_dump($counter);
I want to check the other tables and see if those exists
You can use 'SHOW TABLES' query to locate what tables are existed. After it match it to april-june-2014, july-september-2014, october-december-2014 and jan-march-2015 and etc.
$needTables = array('april-june-2014', 'july-september-2014', 'october-december-2014', 'jan-march-2015')
$existedTables = reportExistedTablesWrapper();//SHOW TABLES
$tables = array_intersect($existedTables, $needTables);
foreach ($tables as $current_table)
{
$queryStr = "SELECT * FROM `$current_table` WHERE ...";
$query = $db->prepare($queryStr);
$query->execute();
while($row = $query->fetch()) {
}
}
try This:
try {
$queryStr = "SELECT * FROM `$current_table` WHERE ...";
$query = $db->prepare($queryStr);
$query->execute();
while($row = $query->fetch()) {
}
} catch(PDOException $e) {
//echo $e->getMessage();
}
finally {
echo "Finally.
";
}