Miguel Vieira Miguel Vieira - 3 months ago 12
MySQL Question

Continue code execution after an error and deal with them later in PHP?

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!

Answer

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

Comments