抛出异常后,jshell继续执行我的脚本。如何让它停止? [英] jshell continues executing my script after exception is thrown. How to make it stop?

查看:135
本文介绍了抛出异常后,jshell继续执行我的脚本。如何让它停止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried writing some jshell scripts. When an exception is thrown, jshell still goes on to execute the next line.

如何使我的脚本更像普通的java程序?

How can I make my scripts behave more like normal java programs?

编辑 :我只是像 jshell SCR.jsh 一样运行。

使用抛出新的异常() 1/0 不要阻止下一行被执行。

Using throw new Exception() or 1/0 does not prevent the next line from being executed.

该脚本包括如下语句:

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

我认为第二行无法访问。这就是我的预期。但是在打印异常后,还会打印 foo

I thought the second line is unreachable. That's what I expected. But after the exception is printed, foo is also printed.

推荐答案

根据我的理解,即使在抛出异常之后, jshell 执行脚本中的所有行也是因为它将您的脚本视为列表 Snippet

As per my understanding, the reason why jshell executes all the lines in your script even after one throws an Exception is since it treats your script as a list of Snippet.


所有表达式都被接受为片段。这包括没有副作用的表达式
,例如常量,变量访问和lambda
表达式:

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))


因此,即使其中一个片段引发异常,其他人也必须遵循 评估打印循环 (REPL)模式。同样自己回答将代码转换为语句块,将其标记为单个代码段当抛出 java.lang.ArithmeticException 时标记其完成。

So even one of the snippet throws an exception, the others must follow the Read-Eval-Print Loop(REPL) pattern. As also answered yourself converting the code as a block of statement marks it as a single Snippet which when throws the java.lang.ArithmeticException marks its completion thereby.

虽然理想情况下,此类陈述应改为定义为声明摘录

Though ideally, such statements should be instead defined as a declaration snippet.


声明摘录( ClassDeclaration InterfaceDeclaration
MethodDeclaration FieldDeclaration )是一个显式
引入了一个名称,可以被其他代码段引用。

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

这篇关于抛出异常后,jshell继续执行我的脚本。如何让它停止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆