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?
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?
Share Improve this question edited Jan 2, 2023 at 20:33 Alexis Wilke 20.9k11 gold badges106 silver badges178 bronze badges asked Apr 13, 2018 at 5:53 user2109254user2109254 1,7593 gold badges33 silver badges53 bronze badges 1- Because 0/1 is well defined? You are dividing 0, not dividing by 0. One is perfectly defined while the other is undetermined. – Jean-Baptiste Yunès Commented Apr 13, 2018 at 6:00
2 Answers
Reset to default 9JavaScript 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));
Nothing is logged because you haven't added any console logs in try block. In JavaScript when you divide a number by 0, the result will be infinity, Now test = infinity. As there is no error it is not going to catch block hence nothing was printed.