抛出异常后,jshell 继续执行我的脚本。如何让它停止?

jshell continues executing my script after exception is thrown. How to make it stop?

我尝试编写一些 jshell 脚本。当抛出异常时,jshell仍然继续执行下一行。

如何让我的脚本表现得更像普通的 java 程序?

编辑:我只是运行喜欢jshell SCR.jsh

使用throw new Exception()1/0不会阻止下一行的执行。

脚本包含如下语句:

System.out.println(1/0)
System.out.println("foo")
/exit

我以为第二行无法访问。这就是我所期望的。但是异常打印出来后,也打印了foo

最后我想我找到了解决方法:

{
    System.out.println(1/0);
    System.out.println("foo");
}
/exit

现在它更接近熟悉的 java 代码。

不仅异常按预期工作,而且分号在块内也是必需的。

据我了解,jshell 执行脚本中所有行的原因即使在抛出异常后也是如此,因为它将您的脚本视为 [=22= 的 列表].

All expressions are accepted as snippets. This includes expressions without side effects, such as constants, variable accesses, and lambda expressions:

1
a
x -> x+1
(String s) -> s.length()

as well as expressions with side effects, such as assignments and method invocations

System.out.println("Hello world");
new BufferedReader(new InputStreamReader(System.in))

因此,即使其中一个片段抛出异常,其他片段也必须遵循 Read-Eval-Print Loop(REPL) pattern. As also 将代码转换为语句块,将其标记为单个 Snippet 抛出 java.lang.ArithmeticException 从而标志着它的完成。

尽管理想情况下,此类语句应改为定义为 声明片段

A declaration snippet (ClassDeclaration, InterfaceDeclaration, MethodDeclaration, or FieldDeclaration) is a snippet that explicitly introduces a name that can be referred to by other snippets.