Well, is it really OK? You are essentially using the exception to control the flow of the code. This is generally considered an anti-pattern (Why not use exceptions as regular flow of control?).
It can easily be avoided by doing the null check yourself:
if (stringValue != null) {
longValue = Long.parseLong(stringValue);
}
However, if you want to keep your code the way it is and let the null
case be handled by the parseLong()
method, you can:
Annotate your method with @SuppressWarnings("ConstantConditions")
@SuppressWarnings("ConstantConditions")
public static void main(String[] args) {
String stringValue = args.length > 0 ? args[0] : null;
long longValue;
try {
longValue = Long.parseLong(stringValue);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("hmm...", e);
}
}
Add a comment //noinspection ConstantConditions
public static void main(String[] args) {
String stringValue = args.length > 0 ? args[0] : null;
long longValue;
try {
//noinspection ConstantConditions
longValue = Long.parseLong(stringValue);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("hmm...", e);
}
}
IntelliJ helped me with both these by pressing alt + enter, bringing up the intentions menu where you can either choose Supress for method or Supress for statement.
However, I think both of these are IDE-specific, so my advise would simply be to let the warning be. Or even better, do the null check yourself.