JavaScript try-catch是否忽略了预期的偶然错误不良做法? [英] Is a JavaScript try-catch ignoring an expected occasional error bad practice?

查看:82
本文介绍了JavaScript try-catch是否忽略了预期的偶然错误不良做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中使用try-catch块并忽略错误而不是在块中测试null中的许多属性是错误的吗?

In JavaScript is it wrong to use a try-catch block and ignore the error rather than test many attributes in the block for null?

try{ 
   if(myInfo.person.name == newInfo.person.name
      && myInfo.person.address.street == newInfo.person.address.street
      && myInfo.person.address.zip == newInfo.person.address.zip) {
         this.setAddress(newInfo);
    } 
} catch(e) {} // ignore missing args


推荐答案

如果您期望某个特定条件,如果您明确测试它,您的代码将更容易维护。我会把上面的内容写成

If you expect a particular condition, your code will be easier to maintain if you explicitly test for it. I would write the above as something like

if(   myInfo && newInfo 
      && myInfo.person && newInfo.person
      && myInfo.person.address && newInfo.person.address
      && ( myInfo.person.name == newInfo.person.name
           && myInfo.person.address.street == newInfo.person.address.street
           && myInfo.person.address.zip == newInfo.person.address.zip
         )
) 
{
     this.setAddress(newInfo);
} 

这使得效果更加清晰 - 例如,假设newInfo全部填写完毕,但myInfo的部分缺失了?也许你真的希望在这种情况下调用setAddress()?如果是这样,你需要改变这个逻辑!

This makes the effect much clearer - for instance, suppose newInfo is all filled out, but parts of myInfo are missing? Perhaps you actually want setAddress() to be called in that case? If so, you'll need to change that logic!

这篇关于JavaScript try-catch是否忽略了预期的偶然错误不良做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆