Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 359
cshu Avatar asked Mar 08 '23 00:03

cshu


1 Answers

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.

like image 185
Naman Avatar answered Apr 29 '23 21:04

Naman