9

I have a piece of code which looks something like this:

try {
  if( !request.body || !request.body.device ) {
    throw new FooError( "missing 'device'" );
  }
  if( !request.body.device.type ) {
    throw new BarError( "missing 'device.type'" );
  }
  if( request.body.device.type != "ios" ) {
    throw new BazError( "unexpected 'device.type'" );
  }
} catch( error ) {
  // handle error and communicate message to the user
}

WebStorm highlights the 3 throw terms and gives the following explanation:

'throw' of exception caught locally

This inspection reports any instances of JavaScript throw statements whose exceptions are always caught by containing try statements. Using throw statements as a "goto" to change the local flow of control is likely to be confusing.

I don't understand that reasoning. Why would this likely be confusing and what would be the less confusing alternative?

Der Hochstapler
  • 19,560
  • 15
  • 87
  • 126
  • 1
    Another thing to consider is that `try ... catch` use in a function means that the JavaScript runtime won't try to optimize the code at all. – Pointy Jun 26 '14 at 15:05
  • @Pointy Oh! Thanks for the heads-up. I'll rewrite my code. – Der Hochstapler Jun 26 '14 at 15:06
  • 1
    @Pointy That is good information, but that is more a failure of the optimizer than it is of good code design. – Loduwijk Jul 25 '17 at 13:47
  • @Aaron it's not so much a failure; it's that code path analysis gets vastly harder in the presence of exception handling. The optimizer has to "choose its battles" I guess. – Pointy Jul 25 '17 at 13:49
  • @Pointy Fine, "that is more a problem (or issue) with the optimizer than of good code design". Maybe I'm spoiled then. I do more with Java, IDE is Netbeans, and their static analysis of exceptions, including try/catch, catches more things than I do when I do manual static analysis; perhaps I am taking it for granted. – Loduwijk Jul 25 '17 at 14:31

0 Answers0