繁体   English   中英

IntelliJ IDEA 检查警告参数可能是 null

[英]IntelliJ IDEA inspection warning argument might be null

有没有办法告诉IDEA以下是可以的:

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);
}

它坚持突出显示stringValue并警告“参数 stringValue 可能为空”。 我知道它可能,但如果是,异常将被捕获。

那么,真的可以吗? 您实际上是在使用异常来控制代码流。 这通常被认为是一种反模式( 为什么不使用异常作为常规控制流? )。

通过 null 检查自己可以轻松避免:

if (stringValue != null) {
  longValue = Long.parseLong(stringValue);
}

但是,如果您想保持代码原样并让parseLong()方法处理null案例,您可以:

使用@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);
  }
}

添加注释//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 通过按alt + enter帮助我解决了这两个问题,调出意图菜单,您可以在其中选择Supress for methodSupress for statement

但是,我认为这两个都是特定于 IDE 的,所以我的建议只是让警告出现。 或者更好的是,自己检查 null。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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