cshu
cshu

Reputation: 5944

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

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

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

Edit: I simply run it like jshell SCR.jsh.

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

The script includes statement like this:

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

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

Upvotes: 4

Views: 434

Answers (2)

Naman
Naman

Reputation: 31888

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.

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

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.

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

Upvotes: 5

cshu
cshu

Reputation: 5944

Finally I think I found a workaround:

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

Now it's much closer to the familiar java code.

Not only exception works just as expected, but semicolons also become necessary inside the block.

Upvotes: 2

Related Questions