Curcuma_
Curcuma_

Reputation: 901

Try-catch block on multiple independent statements

Such that if one statement generates an error I want to keep the flow of execution. I don't want to make as many try catch blocks as statements.

here is an example:

try {
    a = results['a'].data();
    b = results['b'].data();
    c = results['c'].data();
    d = results['d'].data();

} catch (e) {

}

In this case, data are to be retrieved from a dictionary, so whenever the key is undefined, calling data() generates an exception.

Catching which statement generates the exception, or making dummy booleans after each statement and dealing with the rest in final block seems much of a burden to me.

Using JavaScript as a language.

Upvotes: 0

Views: 321

Answers (2)

Viperz0r
Viperz0r

Reputation: 94

You should write a wrapper function to do that. Lets name that function getData for example. Your code would be like this:

// Dummy data
var results = {
    "a": {
        "data": function() {
            return "Hello World";
        }
    }
};

a = getData(results['a'])
b = getData(results['b'])
c = getData(results['c'])
d = getData(results['d'])


function getData(result) {
    try {
        return result.data();
    } catch (e) {

    }
}

Upvotes: 1

Hassan Sadeghi
Hassan Sadeghi

Reputation: 1326

Try this:

;(function(fu){
    a = fu(results,'a', null/*optional default value (for when is not exists)*/);
    b = fu(results,'b');
    c = fu(results,'c');
    d = fu(results,'d');
    //Other Codes...
})(function (r, n, def){return ((r[n]||{}).data||function(){return def;})();});

Upvotes: 1

Related Questions