开发者

Is try / catch (one of) the best ways to keep errors from occuring if a variable is undefined?

I was warned that this post could be too subjective, but I've only been programming for a few weeks, so I'd like to know.

So far I开发者_高级运维've been using try/catch statements in my JS to keep from throwing errors in case a variable isn't defined when a function is run, but is that the only efficient way to do so?


If you're in a browser, you can test for global variables using window.foo. Eg:

if (window.foo === undefined)
    console.log("foo is not defined");

If I was reading code, I would prefer to read this than try { foo } catch { … }.

Also, note the triple equals: that is necessary because, if window.foo is null, then window.foo == undefined will be true, while window.foo === undefined will be false (what you want).


To test if a regular variable exists, I'd say your best bet is to compare the type to undefined, something like:

if (typeof(x) != "undefined") {
    // your variable exists
}


Personally, I try to avoid using try/catch statements if there is a simpler solution.

In your case, JS and every other language provides an easier way to see if a variable is defined.

if (window.x === undefined)

or if the variable was defined using var x:

if (x === undefined)


I wouldn't use try/catch in that circumstance. If it complained that a variable was undefined I'd look for where the bug was and fix it.


Generally, exceptions serve to notify the application that the assumption made by programmer was not satisfied. For example - network connection didn't work, file did not exist, security did not allow something, etc.

If you are aware of the fact that some variable may be undefined, then you should not use exceptions, rather handle that in an if. Or follow a strategy to have meaningful object or value whenever possible.


Check the variable is defined using an if statement

Actually try catch is a very ineffecient way of testing if a variable is undefined. The best way is to check if the variable is defined in an if statement.

if(!someVariable === undefined){
  // Do Logic Here that requires someVariable to be defined
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜