开发者

JSLint complaining about my try/catch

开发者 https://www.devze.com 2023-01-25 20:10 出处:网络
The javascript, when run through JSLint yells at me and I am not sure why. /*jslint browser: true, devel: true, evil: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, newca

The javascript, when run through JSLint yells at me and I am not sure why.

/*jslint browser: true, devel: true, evil: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, newcap: true, immed: true */

var foo = function() {
  try {
    console.log('foo');
  } catch(e) {
    alert(e);
  }
  
  try {
    console.log('bar');
  } catch(e) {
    alert(e);
  }
};

foo();
开发者_运维知识库

It tells me:

Problem at line 12 character 11: 'e' is already defined.

} catch(e) {

It appears to be upset that I have a second catch(e). Why would this be an issue? Does it not simply set e to local variable inside the catch block? Do I need to uniquely name the local variables for all trapped errors in a function?


To JSLint, try..catch has the implicit effect of declaring e as a local variable. Because you have two such blocks within the same function (there is no block scope in JavaScript), JSLint sees that as declaring a variable that has already been declared.

Naming the variables e1, e2, etc. would prevent this warning from JSLint. Is it really a problem though? The ECMAScript 5 specification, section 12.14, says "No matter how control leaves the Block the LexicalEnvironment is always restored to its former state." This, in fact, does appear to be the case:

try {
    throw new Error("testing 1234");
} catch(fooBarBaz){
    alert("Catch: " + fooBarBaz);    // works
}

alert(fooBarBaz);    // throws exception

So, to conclude, this is simply a limitation of JSLint and is unlikely to lead to any practical problem.


Try to use a different variable, maybe its getting confused because e is usually reserved for event handlers.


The JSLint I use shows no error at all - and logical your code is correct.


JSLint might simply be wrong here. According to the ECMAScript spec, entering a catch block creates a new scope inside which the exception variable is defined. In your example, e is valid only inside the catch block and is not defined outside. There is no redefinition here.


Use a different variable for each try / catch.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号