try..catch with setTimeout

try..catch works synchronously. If an exception happens in “scheduled” code, like in setTimeout, then try..catch won’t catch it:

Example:


try {
  setTimeout(function() {
    noSuchVariable; // script will die here
  }, 1000);
} catch (e) {
  alert( "won't work" );
}

To catch an exception inside a scheduled function, try..catch must be inside that function:

setTimeout(function() {
  try {
    noSuchVariable; // try..catch handles the error!
  } catch {
    alert( "error is caught here!" );
  }
}, 1000);