June 18, 201115 yr Hello can anyone explain the use of javascript catch error statement i have seen its used in ajax but whts its use in javascript? i mean to say here that including this code with other javascript helps to find out any errors in the code? Edited June 18, 201115 yr by sash_oo7
June 20, 201115 yr It's a remarkably useful thing so long as it's used properly. The main bonus is when you're building your own library or callback system. Consider the following code: var funcs = []; function myCallBack(func) { funcs.push(func); } function trigger() { for (var i = 0, il = funcs.length; i < il; i += 1) { funcs[i](); } } This is basically what all callback systems look like and they're quite handy for triggering multiple functions at roughly the same time. But now consider a new JavaScripter playing with your code and doing something like this: myCallBack(function () { var notAnArray = 'See? Not an array.'; var errorMaker = notAnArray.splice(); }); myCallBack(function () { actuallyUsefulFunction(); }); When you came to execute your trigger function, the first function in the array would throw an error and stop the entire thing working. Whatever that second function was meant to do, it wouldn't happen as the function would never be called. To get around that, you can catch the errors and do something useful with them, like provide them with a useful notice: function trigger() { for (var i = 0, il = funcs.length; i < il; i += 1) { try { funcs[i](); } catch (e) { // This function could do something helpful like alert the user // to something wrong, including where the error came from // and which function caused the problem. usefulErrorHandler('trigger', e, i); } } } For a really helpful use of the try... catch statement, take a look at the JSLint source code
Create an account or sign in to comment