Sub topic 3
Handling Exceptions and Session Tools in JShell
Assume you have a JDK 9 or later, basic Java syntax, and terminal experience.
Exceptions Without Losing Your Session
An uncaught exception reports its type, message, and stack trace. JShell remains open, so earlier variables and methods remain available.
jshell> Integer.parseInt("abc")
| Exception java.lang.NumberFormatException: For input string: "abc"
| (stack trace lines follow)
jshell> 1 + 1
$2 ==> 2A failed expression does not undo successful earlier snippets. Check the reported line and try a corrected expression.
Editing and Feedback
Press Tab to complete names and inspect available members. Use /edit to open the current session in an external editor. Save or close the editor, then JShell processes the edited snippets.
Feedback controls how much result information JShell prints:
/set feedback concise
/set feedback verbose
/set feedback normal
/set feedback silentnormal is a useful default. Use concise for less noise and verbose when diagnosing declarations or errors.
Scripts and Startup Configuration
A JShell script is a text file containing snippets and commands. For example, save this as demo.jsh:
int x = 10;
System.out.println(x * 2);
/exitRun it with:
jshell demo.jshInside JShell, /save session.jsh writes entered snippets, and /open session.jsh loads them. A startup file can define common imports or helpers:
jshell --startup startup.jshUse /set start -retain startup.jsh to retain that startup choice for later sessions. Use --no-startup when you need a clean session.
External Libraries
Pass a JAR file with --class-path, then import its classes normally:
jshell --class-path lib/mylib.jarThe class path must include every library needed by the snippets you evaluate.
JShell or a Compiled Program?
JShell is useful for experiments, API checks, debugging small expressions, and teaching. A compiled program is better for repeatable builds, automated tests, packaging, version control, and production error handling. JShell also permits interactive redefinition that ordinary Java source rejects, so do not treat every successful experiment as production-ready design.
Embedding JShell
Java programs can evaluate snippets through the jdk.jshell API:
import jdk.jshell.JShell;
public class RunSnippet {
public static void main(String[] args) {
try (JShell shell = JShell.create()) {
shell.eval("int answer = 6 * 7;");
shell.variables().forEach(v ->
System.out.println(v.name() + " = " + v.value()));
}
}
}Compile and run with the jdk.jshell module available.
Exercise
Which JShell command loads snippets from an existing script file?
Show answer
Use /open filename.jsh.