开发者

Is it good to use exception handling in this case?

开发者 https://www.devze.com 2023-03-10 05:45 出处:网络
I am using this kind of code in JavaScript. if(typeof a[x] != \"undefined\" && typeof a[x][y] != \"undefined\" && typeof a[x][y][z] != \"undefined\") {

I am using this kind of code in JavaScript.

if(typeof a[x] != "undefined" && typeof a[x][y] != "undefined" && typeof a[x][y][z] != "undefined") {
    a[x][y][z].update();
}
// else do nothing

I just thought that using try catch to implement the above logic would simplify the code and reduce the checking of three conditions each time. (See below)

try {
    开发者_JAVA技巧a[x][y][z].update();
} catch(e) {
}

Is it good to use try catch in such a situation?

Note: If you are wondering why I am checking the three conditions: a[][][] contains references to objects and the references are added dynamically.


Readability matters more, unless you're in an extremely performance optimized loop or function, it shouldn't make a difference.

As PleaseStand stated, wrapping the whole thing in a try/catch will hide any errors. You could alternatively do something like this, if you still wanted to try/catch

var fn = null;

try {
    fn = a[x][y][z].update;
} catch (e) {
    fn = function(){}
}

fn();

or

var fn = null;

try {
    fn = a[x][y][z].update;
} catch (e) {}

fn && fn();


Any exception thrown by the .update() method is silently ignored, possibly hiding bugs. Note that in your original example, you don't have to use typeof:

if(a[x] !== undefined && a[x][y] !== undefined && a[x][y][z] !== undefined) {
    a[x][y][z].update();
}


Is it good to use try catch in such a situation?

No, as it will catch and discard any other errors than the one you were expecting, making debugging much harder. Unfortunately JavaScript's exception handling is rather weak and gives you no ability to catch only certain exceptions. Instead, you have to catch everything, deliberately sniff for what you want, and re-throw the rest:

try {
    a[x][y][z].update();
} catch(e) {
    if (!(e instanceof TypeError))
        throw e;
}

which isn't very clear, and will still catch quite a lot of other potential errors since JavaScript's built-in exceptions like TypeError are pretty broad.

I would go for your original solution, except using the more explicit in operator instead of the clunky typeof test:

if (x in a && y in a[x] && z in a[x][y])
    a[x][y][z].update();


Why the explicit check for undefined?

if(a[x] && a[x][y] && a[x][y][z]) {
    a[x][y][z].update();
}


Javascript is pretty fault tollerant when it comes to handling falsy values, you could do something like:

var v = 
    (a ? (a[x] 
           ? (a[x][y] 
               ? (a[x][y][z] 
                   ? a[x][y][z] : null) 
               : null) 
           : null) 
    : null);

if (v) v.update();
0

精彩评论

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