Wrong usage of exception - return value from catch
exception, java
Solution
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;
}
}
Problem
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?