0

I am trying to implement try catch block in javascript, but my question is why am i not getting send to the catch block when some error is thrown in my code, for instance

 try {
                var a = 10;
                var b = 0;
                var c = a / b;
            }
            catch (ex) {
                console.log('error');
            }

I have a code like this, now when i try to run this code the result should be an error and should be send into the catch block but i am not getting send into the catch block.

If I use

throw new Error();

in the try catch block, then i get send into the catch block. My question is if i have to manually send it to the catch block then what is the purpose of using try catch block, i could recognize the error myself and may be stop executing my code by using a return statement.

Am i missing something, is there anything i am missing about the try catch block or i dont know, please let me know

Lijin Durairaj
  • 4,910
  • 15
  • 52
  • 85

3 Answers3

3

In JavaScript, division by zero is allowed and produces Infinity, or -Infinity if one part is negative. That's why you're never reaching your catch block.

Pierre-Loup Pagniez
  • 3,611
  • 3
  • 29
  • 29
2

10/0 will return Infinity, it does not throw exception. Try this

    try {                
            adddlert("Error");
   }
   catch (ex) {             
       console.log('error');
   }
Kim Hoang
  • 1,338
  • 9
  • 24
2

Like mentioned, Javascript doesn't throw exception on divide by 0 errors.

But if you want to throw errors, a simple helper function like below should help.

function myDiv(a,b) {
  var r = a / b;
  if (Number.isFinite(r)) return r;
  throw new Error('Divide Error');
}

try {
   var a = 10;
   var b = 0;
   var c = myDiv(a, b);
   console.log(c);
} catch (ex) {
   console.log('error');
}
Keith
  • 22,005
  • 2
  • 27
  • 44