1

Consider following codes:

try{
     throw undefined;
}
catch(someVariable){
    someVariable = 10;
    // do whatever you want with someVariable
    // someVariable will not be a global object at all. (without help of any function scope)
}
// someVariable is no longer valid here

Why some people use this syntax instead of functions when they don't want to declare global variables?

Additional notes:

I've seen this syntax a lot, but the most important one is Google traceur

try {
    throw undefined;
  } catch (a) {
    a = 10;
  }

that it is generated because of the following ecma script 6 syntax:

{
    let a = 10;
}

Google traceur is a ECMA Script 6 parser on older browsers that currently have no support for new JavaScript features.

Yaser Moradi
  • 3,267
  • 3
  • 24
  • 50

3 Answers3

2

Well, there is a difference: Why do catch clauses have their own lexical environment?

try {
     throw undefined;
} catch(someVariable) {
    someVariable = 10; // someVariable will not be global
    var someOtherVariable = 5; // but any declared 'var' will be
}
// someVariable is no longer valid here
console.log(someOtherVariable); // still 5

As you can see, this is just the same behaviour as you would have with

{
    let someVariable = 10;
    var someOtherVariable = 5;
}
console.log(someVariable, someOtherVariable);

It's basically a hack by the Traceur transpiler to create lexical environments for single variables in EcmaScript 5. Probably Google also optimized their browser to recognize this pattern, which explains why it's quite fast on Chrome.

In manually written code, this definitely is to be a bad practise - and without comments, no one knows what this does. Use an IEFE for readability.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

It seems a really bad practice. Exceptions usually slow the execution, and making the system to raise an error an then re-use the error variable is overkill. UPDATE: For me this is a bit shocking: it seems the code is faster when using a try-catch in Chrome, but slower in Firefox and faaaar slower in IE 10: Here is a test I've just created.

Anyway, I think the proper way is using IIEFs like this:

(function () {
    var someVariable=...
    ...
})();

which it's more elegant. Another difference is only the variable with the error is local, any other variable created on the catch block will be global.

Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59
-1

You should use try/catch when it is possible that the operations will cause some error (IOException,...). If there is an error in try it will do what it is in catch. If there is no possibility of error use function.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
gon
  • 26
  • 1