mehras
mehras

Reputation: 51

How to catch a SyntaxError in JavaScript

I am trying to catch a Syntax error in my code, but it does not get into catch block

( function(){
try {

 throw fn(){};  // I am trying to generate some syntax error here

}catch (exception){
    console.log(exception.message);
  }

})();

Edited

If you notice here the wrong syntax is inside the try block, so as a javascript theory it has to first go inside catch block, then whats use of a built-in object SyntaxError

( function(){
try {

throw fn(){};
}catch (exception){
   if(exception instanceof SyntaxError)
   console.log("Syntax Exception occured" + exception.message); 
}
})();

but this is not handled in program instead I am able to see "Uncaught SyntaxError" directly in console

Uncaught SyntaxError: Unexpected token {
    at Object.InjectedScript._evaluateOn (<anonymous>:895:140)
    at Object.InjectedScript._evaluateAndWrap (<anonymous>:828:34)
    at Object.InjectedScript.evaluate (<anonymous>:694:21)

Upvotes: 0

Views: 2339

Answers (1)

ben
ben

Reputation: 3568

You cannot catch syntax error simply because the whole script is not evaluated (due to the syntax error... Only thing I can imagine is to get the code as string, then pass it to eval() and wrap the eval into a try catch...

But earth will collapse if you do that...

var test="var x= 1.5.5;"; //this is a syntax error
var test2="var x=1;"
try {
  eval(test)
  alert(test + ' is a valid script')
} catch(e) {
  alert(test + ' is not a valid script')
}
try {
  eval(test2)
  alert(test2 + ' is a valid script')
} catch(e) {
  alert(test2 + ' is not a valid script')
}

Upvotes: 1

Related Questions