简体   繁体   中英

IntelliJ IDEA inspection warning argument might be null

Is there any way to tell IDEA that the following is OK:

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);
    }
    System.out.println(longValue);
}

It insists on highlighting stringValue and warning "Argument stringValue might be null". I know it might, but if it is, the exception will be caught.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM