Checked exception
In tegenstelling tot RuntimeException moeten alle checked exceptions een try-catch-blok hebben, anders wordt de code niet gecompileerd, laat staan uitgevoerd. In deze oefening zie je dat je een try/catch om een checked exception heen moet zetten, anders zal de applicatie niet compileren en niet uitvoeren.
Deze oefening maakt deel uit van de cursus
Gegevenstypen en uitzonderingen in Java
Oefeninstructies
- Voer de voorbeeldcode zonder wijzigingen uit om te zien dat de aanroep van
Class.forName()om afhandeling vraagt, wat leidt tot een compileerfout (error: compilation failed) als dit niet gebeurt. - Haal de commentaartekens weg bij de try, catch en het bericht dat in het catch-blok wordt getoond.
- Probeer de applicatie nu opnieuw uit te voeren en zie dat deze compilet en draait omdat de checked exception is afgehandeld.
Praktische interactieve oefening
Probeer deze oefening eens door deze voorbeeldcode in te vullen.
public class CheckedExceptionHandling {
public static void main(String[] args) {
// Uncomment the try block
// try {
Class.forName("java.util.ArrayList");
// Uncomment the catch block for ClassNotFoundException
// } catch (ClassNotFoundException e) {
// Uncomment the message for the exception
// System.out.println("Work goes here to recover from the checked exception");
// Uncomment the end of the try/catch
// }
System.out.println("Work complete");
}
}