4

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.

cshu
  • 5,654
  • 28
  • 44
  • 2
    This question would benefit from an example that demonstrates the behavior in question. – David Conrad Sep 22 '17 at 05:37
  • 1
    It would be good to look at a [MCVE](https://stackoverflow.com/help/mcve) for the issue. – Naman Sep 22 '17 at 05:49
  • 1
    Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: How to create a [mcve]. Use the "edit" link to improve your *question* - do not add more information via comments. Thanks! – GhostCat Sep 22 '17 at 08:39

2 Answers2

5

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.

Naman
  • 27,789
  • 26
  • 218
  • 353
2

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.

cshu
  • 5,654
  • 28
  • 44