java - 在不产生无法访问的代码编译错误的情况下中断函数的最少 Java 代码是多少?
问题描述
我想调试一些代码以研究一些行为(并在执行中引入一些强制错误)。我想要么抛出异常,要么在函数完成之前从函数中返回。但是,通过使用throw
or return
(正如用户 @user15244370 在下面的评论中指出的那样)生成无法访问的代码是一个编译错误。
目前我正在使用此代码段来避免检测到无法访问的代码:
if (Math.random() < 1) {
throw new RuntimeException("This is an experiment.");
}
这种强制控制流中断有更紧凑的形式吗?
解决方案
我会说:
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("")
推荐阅读
- java - 升级到 jaxb-runtime 3.0.0 后找不到 ContextFactory
- reactjs - 当过滤器之一更改时获取数据(React.js)
- macos - 有没有办法在 Mac 上的终端中发出 DisableSecureEventInput 命令?
- javascript - 停止 onclick 事件,一旦 onblur 事件激活
- javascript - npm express 的 spuertest 安装问题
- python - discord.py 如何使命令具有权限
- database - 气流 initdb 在 AIRFLOW_HOME 以外的目录中?
- angular - 访问 Angular @ViewChildren 的子组件参考
- html - 使用多个页脚(或页眉)元素作为相邻兄弟元素是否有效?
- flutter - arrayContains 查询的 Firestore 安全规则