3

I had a requirement to check whether a given string is valid JSON or not in Java.

My simple method for that using google gson was:

 public static boolean isValidJson(String str) {
  try {
      gson.fromJson(str, Object.class);
      return true;
  } catch(com.google.gson.JsonSyntaxException ex) { 
      return false;
  }
}

We can use any JSON parser for the same logic, but I haven't seen any inbuilt method to validate json.

Another classic example would be, a custom function to check for number:

public static boolean isNumeric(String str)  
{  
  try  
  {  
    double d = Double.parseDouble(str);  
  }  
  catch(NumberFormatException nfe)  
  {  
    return false;  
  }  
  return true;  
}

My problem is: Is it OK to use exceptions for logics in such manner? OR is it a bad practice?

Tharaka Deshan
  • 1,349
  • 3
  • 15
  • 30
  • 1
    Using `Double.parseDouble(str);` and catching `NumberFormatException` is a question of practicality. There's no `boolean Double.canParse(String)` method, so the developer is likely to use the try/catch to validate input. Same for JSON validation. *But* when you develop your API, avoid forcing your users to rely on thrown exceptions. Offer `boolean` returning methods in this case. – ernest_k Feb 15 '19 at 12:03

2 Answers2

3

The way you are using Exceptions is fine. Micro-optimizations are not something that you will benefit in long run.

When you write the code you should aways try to balance performance vs readability and maintainability.

The penalty from trying catching exception from performance point of view is not that big. It can not justify writing unreadable , or unmaintainable code.

Here is one article that is reviewing how much exactly is the penalty you an see for yourself that the penalty is realy small and if you on't have a specific case that jsutifies optimization you should just go with the flow Do try/catch blocks hurt performance when exceptions are not thrown?

Here for 10 000 000 iterations the difference is just a few miliseconds:

00:00:00.4269033  // with try/catch
00:00:00.4260383
Alexander Petrov
  • 9,204
  • 31
  • 70
1

If possible, try not to use exceptions in the normal flow of your program. Exception handling is pretty slow in java, so if during regular execution of your program a lot of exceptions are thrown and catched, it can have a serious performance impact.

Of course there are exceptions. As you mention above, there is no alternative to using an exception to check validity.

If you do control the code itself, exceptions are not bad, if they will only be thrown in unusual circumstances. If you expect your program to hit the exception very regularly, please try to find some other way.