ชนิดข้อมูลและการจัดการข้อยกเว้นใน Java
Jim White
Java Developer
Error คือปัญหาร้ายแรงที่แอปพลิเคชันรับมือไม่ได้import java.util.*;
public class CauseOutOfMemory {
public static void main(String[] args) {
List<Long> numbers = new ArrayList<Long>();
long counter = 0;
while (true) {
numbers.add(counter);
counter++;
}
}
}
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.base/java.lang.Long.valueOf(Long.java:1204)
at foo/exceptions.CauseOutOfMemory.main(CauseOutOfMemory.java:12)
| Checked Exception | Runtime ("unchecked") Exception | |
|---|---|---|
| ต้องจัดการ | ใช่ | ไม่ |
| สาเหตุทั่วไป | สิ่งที่อยู่นอกเหนือการควบคุม | ความผิดพลาดในการเขียนโค้ด |
| การกู้คืน | กู้คืนได้หากคาดการณ์ไว้ | มักกู้คืนไม่ได้ |
| กลไกการกู้คืน | try/catch หรือ throws | ควรเขียนโค้ดให้รอบคอบเพื่อหลีกเลี่ยง |
| ตัวอย่าง Exception | ไม่พบไฟล์ | ดัชนีอาร์เรย์เกินขอบเขต |
Exception ที่ไม่ใช่คลาสย่อยของ RuntimeException คือ checked exceptionFileNotFoundException)RuntimeException เป็น superclass ของ unchecked exception ทั้งหมดIndexOutOfBoundsException)ArithmeticException)| คลาสย่อยของ RuntimeException | คำอธิบายเงื่อนไขที่เกิดขึ้น |
|---|---|
| ArithmeticException | การคำนวณทางคณิตศาสตร์ที่ผิดพลาด เช่น หารด้วย 0 |
| IndexOutOfBoundsException | ดัชนีที่ใช้กับอาร์เรย์ String ฯลฯ อยู่นอกขอบเขต |
| NegativeArraySizeException | พยายามสร้างอาร์เรย์ที่มีขนาดติดลบ |
int y = 5/0; // ArithmeticException causing code
int[] list = new int[-1]; //NegativeArraySizeException causing code
Exception in thread "main" java.lang.ArithmeticException: / by zero
Exception in thread "main" java.lang.NegativeArraySizeException: -1
public class LoadClass {
public static void main(String[] args) {
Class myClass = Class.forName("com.mysql.Driver");
}
}
LoadClass.java:3: error: unreported exception ClassNotFoundException;
must be caught or declared to be thrown
Class myClass = Class.forName("com.mysql.Driver");
^
1 error
ชนิดข้อมูลและการจัดการข้อยกเว้นใน Java