0

With the following code, I'm trying to count -0.25, -0.333, -0.5, -1, throw exception, then continue counting 1, 0.5, 0.333, 0.25.

So far, I get to the exception, then I'm can't figure out how to continue the counting.

function inverse($x)
{
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    else return 1/$x;
}

try {
    for ($i=-4; $i<=4; $i++) {
        echo inverse($i) . "\n<br>";
        }
}

catch (Exception $e) {
    echo 'Caught exception: ', $e->getMessage(), "\n<br>";

}

// Continue execution
echo 'Hello World';

?>

I've tried adding echo inverse(-$i) . "\n<br>"; into the TRY portion, with no success. It continues the counting, but doesn't catch the exception.

Any suggestions?

Thanks!

3 Answers 3

2

Your catch is outside the for loop, so once the exception is caught, the for loop ends.

Try

for ($i=-4; $i<=4; $i++) {
    try {
        echo inverse($i) . "\n<br>";
    } catch (Exception $e) {
        echo 'Caught exception: ', $e->getMessage(), "\n<br>";
    }
}

instead.

0
0

Or just change your code like this:

 function inverse($x)
    {
        if (!$x) {
            return 'Division by zero.';
        }
        else return 1/$x;
    }

    try {
        for ($i=-4; $i<=4; $i++) {
            echo inverse($i) . "\n<br>";
            }
    }

    catch (Exception $e) {
        echo 'Caught exception: ', $e->getMessage(), "\n<br>";

    }

    // Continue execution
    echo 'Hello World';

    ?>
0

Put the try|catch inside the loop:

for ($i=-4; $i<=4; $i++) {
    try {
        echo inverse($i) . "\n<br>";
    } catch (Exception $e) {
        echo 'Caught exception: ', $e->getMessage(), "\n<br>";
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.