java - JSHELL JDK API:抛出异常时拒绝片段
问题描述
我正在为学生创建一个简单的 jshell 来技术 Java,我想使用 JUNIT 的断言,但是当抛出异常时,片段不被拒绝,我看到它可能需要一个自定义执行引擎,但它太多了。
这是我的代码,它将在 IDE 上运行 REPL,但不会拒绝throw new Exception("Exception message");
package simple.repl;
import java.io.*;
import java.util.List;
import jdk.jshell.*;
import jdk.jshell.Snippet.Status;
public class Main {
public static void main(String[] args) throws IOException {
try (JShell js = JShell.builder().in(System.in).out(System.out).err(System.out).build()) {
for (final String str : System.getProperty("java.class.path").split(File.pathSeparator)) {
js.addToClasspath(str);
}
do {
//input System.out.println("hello");
//int as = 1;
//throw new Exception("Exception message");
System.out.print("Enter some Java code: ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input= reader.readLine();
if (input == null) {
break;
}
List<SnippetEvent> events = js.eval(input);
for (SnippetEvent e : events) {
StringBuilder sb = new StringBuilder();
if (e.causeSnippet() == null) {
// We have a snippet creation event
switch (e.status()) {
case VALID:
sb.append("Successful ");
break;
case RECOVERABLE_DEFINED:
sb.append("With unresolved references ");
break;
case RECOVERABLE_NOT_DEFINED:
sb.append("Possibly reparable, failed ");
break;
case REJECTED:
sb.append("Failed ");
break;
}
if (e.previousStatus() == Status.NONEXISTENT) {
sb.append("addition");
} else {
sb.append("modification");
}
sb.append(" of ");
sb.append(e.snippet().source());
System.out.println(sb);
if (e.value() != null) {
System.out.printf("Value is: %s\n", e.value());
}
System.out.flush();
}
}
} while (true);
}
System.out.println("\nGoodbye");
}
}
解决方案
更新 :
如果 java 代码语法正确,即使在运行时出现异常/错误,片段也会用 Status.VALID 标记,以检查片段异常的使用
snippetEvent.exception() != null
if (snippetEvent.exception() != null) {
System.out.println("Exception : " + snippetEvent.exception().getMessage());
}
推荐阅读
- angular - IE11 中的 Angular 7 和材质渲染不正确
- python - Python 执行另一个文件
- python - Python Sympy求解器在求解三角方程时出错
- python - 重新启用 spacy 的解析器组件给出错误
- python - 如何有效地执行字典合并?
- python-3.x - 功能外观,需要生成一个随机选择 4 个选项的列表
- angular - 运行业力单元测试用例“引发未知 [对象对象]”时出错
- python - 我的时间序列图如何从“00:00”开始并在“23:00”结束?两边没有空格
- asp.net-mvc - 在 Bamboo 中设置 NSIS 构建
- java - 从另一个类调用时函数崩溃应用程序但从 MainActivity.java 调用时不会