eccezioni checked e unchecked
Ci si riferisce alle RuntimeException (e le sue sottoclassi) come unchecked exception. Tutte le altre eccezioni (ovvero tutte quelle che non derivano da RuntimeException), vengono dette checked exception. Se si utilizza un metodo che lancia una checked exception senza gestirla da qualche parte, la compilazione non andrà a buon fine. Da qui il termine checked exception (in italiano “eccezioni controllate”).Si consideri questo codice :
import java.io.IOException;
public class Main {
String nome;
int numero;
public static void main(String[] args) {
Main classe = new Main();
System.out.println(classe.nome);
}
void metodo (){
throw new RuntimeException();
}
void metodo2 () throws IOException{
throw new IOException();
}
void metodo3 (){
try {
throw new IOException();
} catch (IOException
e) {
e.printStackTrace();
}
}
}
Il metodo metodo() compila anche se non si gestisce l'eccezione. Infatti essa è di tipo unchecked.Invece l'eccezione IO è di tipo checked e va gestita, o con un throws oppure con un try catch, altrimenti i metodi metodo2() e metodo3() non compilano.
Nessun commento:
Posta un commento