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 testing for "parsability", 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 an "exceptional" situation (and not the regular case) this looks 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 for certain numeric types 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, and input
be an integer value, not a floating point. 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
it boils down to a matter of taste which construct to use. Note the try/catch might be beneficial in cases where the numerical calculations are more complex and you would have to check more than just one denominator, or multiple lines for validity (assumed you don't want individual treatment for different error situations).
So in short: there is no braindead "one size fits all solution", you have to look at the real individual case, the language, the provided features, the specific requirement, and not at some sloppily written pseudo-code out of context. Make yourself aware of the semantical differences and the performance differences, and then decide which elements to use.
See also: Arguments for or against using Try/Catch as logical operators
string is JSON
do? Probably a function that tries to parse the string, catches an exception and returning false if parsing fails.string is JSON
does attempt to parse the string, doing something likeif (string is JSON) { parser.parse(string) }
is duplicating work and therefore probably bad if this is anywhere near your hot path. Ifstring is JSON
works some other way, it could be a good idea. Please include the details in the question as to whatstring is JSON
does.