Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Use of javascript catch error statement

Featured Replies

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

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.