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.

Sign up to request clarification or add additional context in comments.

Comments

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';

    ?>

Comments

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>";
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.