MulaiMulai sekarang secara gratis

Checked exception

Opposite of RuntimeException, all checked exceptions must have a try-catch block or the code will not compile, let alone run. In this exercise, you will see that you must add a try/catch around a checked exception, or else the application will not compile and will not run.

Latihan ini adalah bagian dari kursus

Data Types and Exceptions in Java

Lihat Kursus

Petunjuk latihan

  • Run the sample code without any changes to see that the call to Class.forName() requires handling, leading to a compile error (error: compilation failed) if it is not handled.
  • Uncomment the try, catch, and message displayed in the catch block.
  • Now, try to run the application again and see that the application will compile and run because the checked exception has been handled.

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

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");
	}
}
Edit dan Jalankan Kode