JShell และ Exception Handling
ใน Java 9 JShell จัดการ exception ให้โดยอัตโนมัติ ไม่ต้องเขียน try-catch เอง JShell จะจับ exception ทั้ง checked และ unchecked แสดงข้อมูล แล้วกลับมาที่ prompt ให้ทำงานต่อได้ทันที
ตัวอย่าง 1: ArrayIndexOutOfBoundsException (Unchecked)
jshell> int[] values = {10, 20, 30}
values ==> int[3] { 10, 20, 30 }
jshell> values[4]
| java.lang.ArrayIndexOutOfBoundsException thrown: 4
| at (#7:1)
ตัวอย่าง 2: FileNotFoundException (Checked)
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.<init> (FileInputStream.java:139)
| at FileInputStream.<init> (FileInputStream.java:94)
| at (#5:1)
ตัวอย่าง 3: ArithmeticException (Unchecked)
jshell> 1/0 | java.lang.ArithmeticException thrown: / by zero | at (#4:1)
ข้อดีของการจัดการอัตโนมัติ
- ลด boilerplate code สำหรับการทดลอง
- เห็น stack trace ทันทีโดยไม่ต้อง run แอปทั้งหมด
- ทำงานต่อได้เลยหลังจาก exception (session ไม่จบ)
- รองรับทั้ง checked และ unchecked exceptions
สรุป
JShell ทำให้การทดสอบโค้ดที่อาจโยน exception ง่ายขึ้นมาก เหมาะสำหรับการ explore API และ prototype