Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a JavaScript try-catch ignoring an expected occasional error bad practice?

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
like image 456
user22816 Avatar asked Sep 26 '08 19:09

user22816


People also ask

Is it bad practice to use try catch?

Without a try catch, you run the risk of encountering unhandled exceptions. Try catch statements aren't free in that they come with performance overhead. Like any language feature, try catches can be overused.

Should you avoid try catch?

When Should You Avoid Using Try-Catch? If you know an error is likely to happen, you shouldn't use the try-catch statement since you'd rather debug the problem than disguise it.

Which kind of error should you typically handle via try catch?

So, try... catch can only handle errors that occur in valid code. Such errors are called “runtime errors” or, sometimes, “exceptions”. That's because the function itself is executed later, when the engine has already left the try...

Is try catch best practice?

Use try/catch/finally blocks to recover from errors or release resources. Use try / catch blocks around code that can potentially generate an exception and your code can recover from that exception. In catch blocks, always order exceptions from the most derived to the least derived.


1 Answers

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);
} 

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!

like image 143
moonshadow Avatar answered Sep 24 '22 06:09

moonshadow