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?
Without a try catch, you run the risk of encountering unhandled exceptions. Try catch statements aren't free in that they come with performance overhead. Like any language feature, try catches can be overused.
Place any code statements that might raise or throw an exception in a try block, and place statements used to handle the exception or exceptions in one or more catch blocks below the try block. Each catch block includes the exception type and can contain additional statements needed to handle that exception type.
The reason why your try catch block is failing is because an ajax request is asynchronous. The try catch block will execute before the Ajax call and send the request itself, but the error is thrown when the result is returned, AT A LATER POINT IN TIME. When the try catch block is executed, there is no error.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With