Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong usage of exception - return value from catch

Tags:

java

exception

This is the piece of code.

  private boolean CheckTerm()
      {
          String str = lGskCompoundNumber;
          if (lPrefix.trim() == "" || lNumber.trim() == "")
              return false;

          try
          {
              Integer.parseInt(lNumber);
          }
          catch (Exception ex)
          {
              return false;
          }
          if (lHasAmpersand)
              str = lGskCompoundNumber.replace("&", "");
          return str.equals(lPrefix + lInitSep + lNumber + lEndSep + lSuffix);
      }

Should I return a certain value from catch block or is the usage right?

like image 609
dev Avatar asked Nov 30 '22 23:11

dev


2 Answers

This code is correct and does not look suspicious. When parsing fails (note that you should catch the most narrow exception possible, NumberFormatException in this case), whole validation failed, so you are returning false. Otherwise you are performing additional checks (after catch block) and returning their result. This code is fine.

If you find it a bit hard to read, consider the following refactoring:

private boolean checkTerm() {
    try
        {
            String str = lGskCompoundNumber;
            if (lPrefix.trim() == "" || lNumber.trim() == "")
                return false;
            Integer.parseInt(lNumber);
            if (lHasAmpersand)
                str = lGskCompoundNumber.replace("&", "");
            return str.equals(lPrefix + lInitSep + lNumber + lEndSep + lSuffix);
        }
        catch (NumberFormatException ex)
        {
            return false;
        }
    }
like image 194
Tomasz Nurkiewicz Avatar answered Dec 04 '22 11:12

Tomasz Nurkiewicz


There's nothing wrong in your code but I always prefer to have a single exit point in my methods, so I prefer to write something like:

private boolean CheckTerm()
{
    boolean res = false;
    String str = lGskCompoundNumber;
    if (lPrefix.trim() == "" || lNumber.trim() == "")
    {
    }
    else
    {
        try
        {
            Integer.parseInt(lNumber);
            if (lHasAmpersand)
                str = lGskCompoundNumber.replace("&", "");
            res = str.equals(lPrefix + lInitSep + lNumber + lEndSep + lSuffix);
        }
        catch (NumberFormatException ex)
        {
        }

    }
    return res;
}
like image 30
davioooh Avatar answered Dec 04 '22 10:12

davioooh