首页 > 解决方案 > 在不产生无法访问的代码编译错误的情况下中断函数的最少 Java 代码是多少?

问题描述

我想调试一些代码以研究一些行为(并在执行中引入一些强制错误)。我想要么抛出异常,要么在函数完成之前从函数中返回。但是,通过使用throwor return(正如用户 @user15244370 在下面的评论中指出的那样)生成无法访问的代码是一个编译错误。

目前我正在使用此代码段来避免检测到无法访问的代码:

if (Math.random() < 1) {
    throw new RuntimeException("This is an experiment.");
}

这种强制控制流中断有更紧凑的形式吗?

标签: java

解决方案


我会说:

x();

// or if you want to specify your own exception:

y(() -> new RuntimeException("..."));

我省略了样板:

import static foo.Bar.*;

// and:

public class Bar {
  public static void x() {
    if(true) { // this will just give a dead code warning, no error
      // alternative: 1==1
      throw new RuntimeException();
    }
  }

  public static void y(Supplier<RuntimeException> s) {
    if(...) {
      throw s.get();
    }
  }
}

要省略警告,您可以使用更复杂的表达式,例如"".equals("")


推荐阅读