javascript

Why doesn't Javascript handle divide by zero error in a try catch


I have the following simple code that throws an error in a try/catch and the error is handled in the catch. This works as expected, and the error is logged:

try {
    throw new Error('Test Error');
} catch (err) {
    console.log('Caught Error:');
    console.log(err);
}

Then I try the next example where the code throws an error rather than me just creating a test Error and throwing it, and the error is suppressed, but not handled in the catch:

try {
    let test = 1 / 0;
} catch (err) {
    console.log('Caught Error:');
    console.log(err);
}

In this second example, nothing is logged. Why is this?


Solution

  • JavaScript hasn't that kind of exception, is just returns a special value called Infinity.

    You can check with Number.isFinite function and detect if it was divided on 0.

    console.log(Number.isFinite(1 / 0));
    console.log(Number.isFinite(1 / 1));