I have never used Try-catch in my code before, but now I need to do it and it seems that I don’t quite understand the way it works. I have data in a string which I get using explode:
$groupNumbers = array();
$str = $dataGroups['groups'];
$groupNumbers = explode(",", $str);
$count = count($groupNumbers);
Then I want to check if every element is numeric, and if it is I proceed with a database query, otherwise I want to abort the action ant return some error.
Here is what I’m doing:
for ($i = 0; $i < $count; ++$i)
{
try
{
is_numeric($groupNumbers[$i]);
}
catch (Exception $ex)
{
process_exception_to_json($ex);
}
}
and if evrery element is numeric I construc an active record to do SQL:
$this->db->insert_batch(‘users_groups’, $datas);
Obviously written like that, even if an element is not numeric the action is not aborted and I the insert_batch is still executed with unvalid values which is waht I want to avoid. What is the exact way of doing this, so I can get an exception, and abort the action at the same time.
Thanks
Leron
This is because
is_numericDocs does not throws an exception but returns a value. It will never fail / throw an exception.You would need to do it this way (just an example, I don’t suggest it as it’s superfluous):
Instead create your own group numbers type:
With the following type:
The string processing is now encapsulated, no more outer-loops and
GroupNumbersdoes only instantiate if there are actual numbers in the string.If you’re not fluent with classes, you can have similar benefits as well with a procedural style. It’s probably easier to understand (but pretty much the same):