Tipe Data dan Exception di Java
Jim White
Java Developer
Error adalah masalah seriusimport 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 | |
|---|---|---|
| Perlu penanganan | Ya | Tidak |
| Penyebab umum | Di luar kendali kita | Kesalahan pemrograman |
| Pemulihan | Biasanya bisa dipulihkan jika diantisipasi | Biasanya tidak bisa dipulihkan |
| Mekanisme | try/catch atau throws | Sebaiknya dicegah dengan kode yang baik |
| Contoh | File tidak ditemukan | Indeks array di luar batas |
Exception yang bukan subkelas RuntimeException adalah checked exceptionFileNotFoundException)RuntimeException adalah superclass untuk semua unchecked exceptionIndexOutOfBoundsException)ArithmeticException)| Subkelas RuntimeException | Kapan dilempar |
|---|---|
| ArithmeticException | Perhitungan tidak valid, mis. membagi 0 |
| IndexOutOfBoundsException | Indeks pada array, String, dll. di luar rentang |
| NegativeArraySizeException | Membuat array dengan ukuran negatif |
int y = 5/0; // Kode penyebab ArithmeticException
int[] list = new int[-1]; //Kode penyebab NegativeArraySizeException
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
Tipe Data dan Exception di Java