Search code examples
javascripttry-catch-finally

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


Solution

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

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