Tipi di dati ed eccezioni in Java
Jim White
Java Developer
Error indica un problema graveimport 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)
| Eccezione checked | Eccezione runtime ("unchecked") | |
|---|---|---|
| Richiede gestione | Sì | No |
| Causa generale | Fattori fuori dal nostro controllo | Errori di programmazione |
| Recupero | Di solito possibile se previsto | Di solito non recuperabile |
| Meccanismo di recupero | try/catch o throws | Meglio evitarle con buon codice |
| Esempio di eccezione | File non trovato | Indice array fuori limite |
Exception che non sono anche sottoclassi di RuntimeException sono checked exceptionsFileNotFoundException)RuntimeException è la superclasse di tutte le unchecked exceptionsIndexOutOfBoundsException)ArithmeticException)| Sottoclasse di RuntimeException | Quando viene lanciata |
|---|---|
| ArithmeticException | Operazioni aritmetiche errate, es. divisione per 0 |
| IndexOutOfBoundsException | Indice per array, String, ecc. fuori intervallo |
| NegativeArraySizeException | Creazione di un array con dimensione negativa |
int y = 5/0; // Codice che causa ArithmeticException
int[] list = new int[-1]; //Codice che causa 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;
deve essere gestita o dichiarata come lanciata
Class myClass = Class.forName("com.mysql.Driver");
^
1 error
Tipi di dati ed eccezioni in Java