Reputation: 154
I'm coding a simple php code for sending e-mails from a MySQL table with a mailing list;
I'm doing the best I can to prevent errors from happening, to validate fields and do everything I can to prevent errors from happening.
I'm going to use a foreach loop to send each e-mail with names and other relevant information, but I'm worried that for some reason, some e-mail or name might raise an error and stop my code halfway through the list, leaving me with no way of knowing where it stopped.
I want to know if there's a way to skip the problematic row and keep on sending the e-mails, and then show details about the rows it failed sending.
I thought that I could use Try/Catch but I couldn't find if I could continue the code after the exception, and couldn't find how to append error mesages to display at the end.
If this isn't a good way to deal with possible errors, what's the best way?
Thanks in advance!
Upvotes: 3
Views: 5965
Reputation: 41820
try/catch
will definitely work for this. Since you're specifically concerned with continuing execution after the exception, keep in mind that it matters what is included in the try
block. For example:
$array = [1, 2, 3, 'string', 5, 6];
try {
foreach ($array as $number) {
if (is_string($number)) throw new Exception("Not a number", 1);
echo $number;
}
} catch (Exception $e) {
echo $e->getMessage();
}
with this code you would see
123Not a number
because after the exception is handled, execution will continue after the catch block, not at the point the exception was thrown.
Whereas, with the try/catch inside the foreach loop
foreach ($array as $number) {
try {
if (is_string($number)) throw new Exception("Not a number", 1);
echo $number;
} catch (Exception $e) {
echo $e->getMessage();
}
}
the loop would continue after the exception and you would see
123Not a number56
Upvotes: 6
Reputation: 57
You can use try cacth to ignore errors
try {
// your code here
} catch (Exception $e) {
// here do nothing
}
If you want deal wjth the errors later, you could add exceptions to array and deal with the errors on finally block.
try {
// your code
} catch (Exception $e) {
// add error to error array
} finally {
// deal with error array
}
http://php.net/manual/pt_BR/language.exceptions.php
Upvotes: 1
Reputation: 21
Did you try the try/catch solution? It is perfectly described here: http://php.net/manual/en/language.exceptions.php
"Normal execution (when no exception is thrown within the try block) will continue after that last catch block defined in sequence."
So you could put your send-function into a try/catch block -> if an error occurs write the error in an array and print the array after the foreach loop.
Upvotes: 2