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.

Example-1

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.

Example-2

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


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

Example-3

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