Sub topic 10
Handling exceptions without losing your session
This chapter assumes you can start JShell and enter expressions, variables and methods, as covered in the earlier chapters. You should also know Java's try/catch syntax and the difference between checked and unchecked exceptions.
What happens when a snippet throws
In a compiled program, an uncaught exception ends the program. In JShell it ends only the snippet that threw it. JShell prints the exception, then returns to the prompt with every earlier variable, method and class still defined.
jshell> int ratio(int a, int b) { return a / b; }
| created method ratio(int,int)
jshell> ratio(10, 0)
| Exception java.lang.ArithmeticException: / by zero
| at ratio (#1:1)
| at (#2:1)
jshell> ratio(10, 2)
$3 ==> 5The report has two parts. The first line gives the exception class and message. The "at" lines are the stack trace. Frames from your own snippets appear as (#N:L), where N is the snippet id (the number /list shows) and L is the line within that snippet. In the example, ratio (#1:1) is line 1 of snippet 1, and (#2:1) is the call you typed. Frames from JDK classes appear with their file and line number as usual.
Notice the scratch variable number. The failed call ratio(10, 0) was snippet 2 and produced no value, so no $2 exists. The next successful expression is $3.
Compile errors are not exceptions
Two kinds of failure look similar but differ in when they happen.
- A compile error means JShell could not build the snippet. It prints
Error:with the problem, and the snippet is never run or recorded. - An exception means the snippet compiled and started running, then failed.
jshell> int n = "five"
| Error:
| incompatible types: java.lang.String cannot be converted to int
| int n = "five";
| ^----^
jshell> Integer.parseInt("five")
| Exception java.lang.NumberFormatException: For input string: "five"
| at NumberFormatException.forInputString (NumberFormatException.java:67)
| at Integer.parseInt (Integer.java:661)
| at (#2:1)The JDK line numbers in the second trace depend on your JDK version. Only the first line and the (#2:1) frame are stable.
Variables that fail during initialization
If the initializer of a variable declaration throws, the variable still exists. It holds the default value for its type: 0, false or null.
jshell> int total = 100 / 0;
| Exception java.lang.ArithmeticException: / by zero
| at (#1:1)
jshell> total
total ==> 0This can mislead you. A later snippet may read total and appear to work on a value that never got assigned. If you see an exception during a declaration, check /vars or redeclare the variable before relying on it.
Checked exceptions need no handling
At the top level, JShell does not enforce the "catch or declare" rule. You can call methods that throw checked exceptions directly.
jshell> Thread.sleep(100)
jshell> new java.io.FileReader("missing.txt")
| Exception java.io.FileNotFoundException: missing.txt (No such file or directory)
| at FileInputStream.open0 (FileInputStream.java:-2)
| at FileInputStream.open (FileInputStream.java:213)
| at FileInputStream.<init> (FileInputStream.java:152)
| at FileReader.<init> (FileReader.java:75)
| at (#2:1)This is a convenience for experiments. The rule still applies inside a method body, so the following needs a throws clause:
jshell> void pause() throws InterruptedException { Thread.sleep(50); }
| created method pause()
jshell> pause()Do not assume code that works as a bare snippet compiles in a real class. A FileReader call that ran fine at the prompt will be rejected by javac unless you handle or declare FileNotFoundException.
Catching exceptions in a session
Normal try/catch blocks work. A common pattern is to catch an exception and keep it in a variable so you can inspect it after the block finishes.
jshell> Exception saved = null
saved ==> null
jshell> try { Integer.parseInt("abc"); } catch (Exception e) { saved = e; }
jshell> saved.getMessage()
$3 ==> "For input string: \"abc\""
jshell> saved.getClass().getSimpleName()
$4 ==> "NumberFormatException"Declare the variable before the try. A variable declared inside the block would disappear when the block ends, because the whole try statement is one snippet. Later you can call saved.printStackTrace() to see the full trace again.
A method can also hide an exception from the prompt:
jshell> int parseOr(String s, int fallback) {
...> try { return Integer.parseInt(s); }
...> catch (NumberFormatException e) { return fallback; }
...> }
| created method parseOr(String,int)
jshell> parseOr("12", -1) + parseOr("x", -1)
$2 ==> 11Errors, stuck snippets and System.exit
Exceptions are not the only failures. Errors such as StackOverflowError are thrown too, and JShell reports them the same way while keeping the session alive.
jshell> int down(int n) { return down(n + 1); }
| created method down(int)
jshell> down(0)
| Exception java.lang.StackOverflowError
| at down (#1:1)
| at down (#1:1)
| ...A snippet that never finishes needs a different fix. Press Ctrl+C while it runs. JShell interrupts the snippet and returns to the prompt with your state intact.
jshell> while (true) { }
^C
jshell>System.exit is a special case. JShell runs your snippets in a separate process, so calling System.exit(0) ends that process and not JShell itself. JShell reports that the execution state was lost and tells you how to recover it.
jshell> System.exit(0)
| State engine terminated.
| Restore definitions with: /reload -restoreRunning /reload -restore replays your earlier snippets, which rebuilds your definitions. It also re-runs every expression and statement, so any side effects happen again. Use /exit to leave JShell itself.
Choosing a recovery action
| Situation | What you see | What to do |
|---|---|---|
| Compile error | `Error:` with a caret under the problem | Retype the snippet. Nothing was recorded. |
| Exception from an expression | `Exception ...` and a stack trace | Fix the input and rerun. No `$N` was created. |
| Exception in a variable initializer | `Exception ...`, variable exists with default value | Redeclare the variable. |
| Snippet never returns | Prompt does not come back | Press Ctrl+C. |
| `System.exit` called | `State engine terminated.` | Run `/reload -restore`. |
Common mistakes
- Treating a variable from a failed declaration as if it held a real value.
- Declaring the holder variable inside the
tryblock and then finding it undefined afterwards. - Assuming that code without
try/catchat the prompt will compile inside a class. - Calling
System.exitto "stop" a loop, which discards the execution state.
Exercise
You enter String s = null; and then s.length(). JShell prints a NullPointerException. What is the state of s afterwards, and is a scratch variable such as $2 created for the failed call?
Show answer
s is still defined and still holds null, because the exception came from the second snippet and not from the declaration. No scratch variable is created for s.length(), because the snippet produced no value. The next successful expression gets the next unused number.
Exercise
You run int count = Integer.parseInt("x"); and see a NumberFormatException. Then you enter count + 1 and get $2 ==> 1. Why did that work, and what should you do?
Show answer
The failed initializer still declared count, holding the default value 0, so count + 1 evaluated to 1. The value is misleading because the parse never succeeded. Redeclare the variable with a valid value, for example int count = Integer.parseInt("5");, or check /vars after any exception during a declaration.