Sub topic 10
Handling Exceptions Without Losing Your JShell Session
Assume you have a JDK 9 or later, basic Java syntax, and experience using a terminal. An exception is an object that reports an error while Java is evaluating code. In a compiled program, an uncaught exception usually ends the current execution. In JShell, an uncaught exception ends only the current snippet. The session remains available.
Observe an Uncaught Exception
Start JShell and evaluate an invalid conversion:
jshell> Integer.parseInt("abc")
| Exception java.lang.NumberFormatException: For input string: "abc"
| at Integer.parseInt (Integer.java:...)
| at ...The exact stack-trace lines depend on the JDK version. NumberFormatException means that Java could not convert the text into an integer.
The exception does not erase earlier variables or methods. You can continue entering snippets:
jshell> int limit = 5
limit ==> 5
jshell> Integer.parseInt("abc")
| Exception java.lang.NumberFormatException: For input string: "abc"
jshell> limit * 2
$3 ==> 10The failed expression does not create a useful result variable. The session state before the expression remains intact.
Catch an Exception in the Session
You can handle an expected error with a try statement. A try statement contains code that might fail. A catch block runs when it catches a matching exception type.
jshell> try {
...> int value = Integer.parseInt("abc");
...> System.out.println(value);
...> } catch (NumberFormatException ex) {
...> System.out.println("Invalid integer: " + ex.getMessage());
...> }
Invalid integer: For input string: "abc"The variable value exists only inside the try block. The exception object ex exists only inside the catch block. This scope rule is the same as in ordinary Java source.
You can use a variable declared outside the statement when you need the result afterward:
jshell> int parsed = -1
parsed ==> -1
jshell> try {
...> parsed = Integer.parseInt("42");
...> } catch (NumberFormatException ex) {
...> System.out.println("Keeping the previous value");
...> }
jshell> parsed
parsed ==> 42If parsing fails, parsed keeps its previous value, provided the assignment has not already changed it.
Continue or Reset Deliberately
Use /vars and /methods to check what survived. If a declaration became invalid or a variable contains an unwanted value, redefine it or remove it with /drop.
Use /help when you need command syntax:
jshell> /help /varsThe most useful rule is to treat each snippet as an experiment. Let unexpected exceptions reveal the failing input, inspect the state, and then run a corrected snippet. Restart JShell only when you need a completely clean environment.
Exercise
After int total = 10, an expression throws an uncaught exception. What happens to total, and how can you verify it?
Show answer
total remains available because the exception ends only the failed snippet. Enter total or run /vars to verify its value.