Lijin Durairaj
Lijin Durairaj

Reputation: 5232

Not able to reach catch block in javascript

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

Upvotes: 0

Views: 864

Answers (3)

Pierre-Loup Pagniez
Pierre-Loup Pagniez

Reputation: 3761

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.

Upvotes: 3

Keith
Keith

Reputation: 24181

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

Upvotes: 2

Kim Hoang
Kim Hoang

Reputation: 1368

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

    try {                
            adddlert("Error");
   }
   catch (ex) {             
       console.log('error');
   }

Upvotes: 2

Related Questions