Skip to main content
1 of 4
Doc Brown
  • 214k
  • 34
  • 394
  • 603

The problem here is most probably that your JsonParser does neither have a method isJson, nor does it have a method tryParse (which could avoid the duplicate work which would be involved in first is if an input is "parseable", and then parse again to get the actual result). So I guess you have no other option than catching the exception. But that's not "wrong" or bad - assumed getting a non-valid Json string is indeed an "exceptional" situation this feels pretty natural.

In case your JsonParser would provide a tryParse method, it might be a good idea to use it instead of try/catch, since the resulting code would be a little bit shorter. However, to some degree this is still a matter of taste.

One issue with your second example is that in certain programming languages a "division-by-zero" does not necessarily throw an exception, some languages have a number representation "Infinity", at least for floating point math.

But let's assume this to be a case where an exception would be thrown. Then we see another issue here: the test if(input > 0) is not semantically equivalent to the implicit test done in the try/catch variant (which is if(input != 0)). So the if/else construct allows you to place a different, more strict validation into a single line. If that's what you want or need, the if/else is obviously the more correct choice.

Another thing might be performance: in lots of languages throwing an exception might be more costly than making an explicit test beforehand. However, in cases where a zero denominator occurs seldom, this might be negligible. So in case

  • you want a test for the denominator to be unequal to zero

  • the performance hit of the exception is negligible

it boils down to a matter of taste which construct to use.

So in short: there is no braindead "one size fits all solution", you have to look at the individual case, be aware of the semantical differences and the performance differences, and then decide.

Doc Brown
  • 214k
  • 34
  • 394
  • 603