When should you use try/catch in JavaScript?

后端 未结 7 932
旧时难觅i
旧时难觅i 2021-01-30 00:53

When I\'m developing normal web application with JavaScript, the try/catch statement is not needed usually. There\'s no checked exception, File IO or database conne

7条回答
  •  南笙
    南笙 (楼主)
    2021-01-30 01:29

    One scenario I find try/catch/finally useful is with deeply nested objects where a null can pop up at any level. for example, consider this:

    var something = one.two.three.four.five;
    

    to perform this "get" with 100% safety one would have to write a bit of verbose code:

    if(one && one.two && one.two.three && one.two.three.four)
       something = one.two.three.four.five;
    

    Now imagine the variable names are realistic and longer and you quickly get a very ugly code if statement.

    I tend to use try/catch/finally to simplify this when I don't care about any "else" scenarios and just want the object or not:

    var something;
    try { something = one.two.three.four.five; }
    catch { something = "default"; }
    finally { doSomething(something); }
    

提交回复
热议问题