![](/img/trans.png)
[英]In jdk7 watch service API, when will the OVERFLOW event be thrown?
[英]JSHELL JDK API : Reject snippet when exception is thrown
我正在為學生創建一個簡單的 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());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.