How to handle an exception in JShell in Java 9?

JavaObject Oriented ProgrammingProgramming

In Java 9, JShell provides a fast and friendly environment that enables us to quickly explore, discover, and experiment with Java language features and extensive libraries.

In JShell, manually catching the exceptions is not required. JShell automatically catches each exception and displays information about it, then displays the next JShell prompt so we can continue our session. It works for unchecked exceptions also. By automatically catching both checked and unchecked exceptions, JShell makes it easier for us to experiment with methods that throw checked exceptions.

In the below example, ArrayIndexOutOfBoundsException has occurred because the value of "values[4]"  not found.


jshell> int[] values = {10, 20, 30}
values ==> int[3] { 10, 20, 30 }

jshell> values[4]
|   java.lang.ArrayIndexOutOfBoundsException thrown: 4
|        at (#7:1)

In the below example, FileNotFoundException has occurred because the file not found in the directory.


jshell> FileInputStream fis = new FileInputStream("data.txt")
| thrown: data.txt (The system cannot find the file specified)
|       at FileInputStream.open0 (Native Method)
|       at (
|       at FileInputStream. (
|       at FileInputStream. (
|       at (#5:1)

In the below example, ArithmeticException (unchecked exception) has occurred because the value of "1/0" is undefined.


jshell> 1/0
|  java.lang.ArithmeticException thrown: / by zero
|        at (#4:1)
Updated on 25-Feb-2020 10:13:32