created on | January 28, 2022 |
If a snippet throws an exception, jshell prints the exception together with the snippet id that caused the exception and the line number of the snippet where the Exception is thrown. The general form for printing snippet id and line number of snippet is:
If an exception is thrown in a method, the method name and line number as well as the snippet id and the line number of the snipped that invoked the method are printed out.
The following excerpt of a jshell session shows an exception thrown in a statement and an axception thrown in a method:
Since the jshell is a REPL (Read Evaluate Print Loop), an Exception thrown in a snippet does not affect the subsequent snippets. However, the jshell exhibits some other unexpected behaviour in some cases where an Exception is thrown.
Given the following three snippets
and running the snippets one can expect snippet #2 to fail with an ArithmeticException, which is indeed indicated by jshell:
Nevertheless the variable declared and initialized in snippet #2 has been initialized and has been assigned a value of 0:
The problem here is that if an Exception is thrown in a snippet, jshell still returns a value from that snippet and happily assignes this value to a variable (explicitly declared variable or implicit variable). I find this rather odd.