In Java, exceptions are used to handle errors that occur during the execution of a program. Exceptions can be divided into two categories: checked exceptions and unchecked exceptions.
Checked exceptions are exceptions that are checked by the compiler at compile-time. These exceptions are typically used to indicate conditions that are recoverable, such as file I/O errors or network errors. When a method throws a checked exception, the calling method must either handle the exception or declare that it can also throw the exception.
Here’s an example of a method that throws a checked exception:
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader reader =
new BufferedReader(new FileReader("myfile.txt"));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
reader.close();
}
}
In this example, the main method reads lines from a file using a BufferedReader and a FileReader. The readLine method of the BufferedReader can throw an IOException, which is a checked exception that must be handled or declared by the calling method.
In this case, we declare that the main method can also throw the IOException exception using the throws keyword. This means that any method that calls the main method must also handle or declare the IOException exception.
Unchecked exceptions, on the other hand, are exceptions that are not checked by the compiler at compile-time. These exceptions are typically used to indicate programming errors, such as null pointer exceptions or array index out of bounds exceptions. Unchecked exceptions are also known as runtime exceptions.
Here’s an example of a method that throws an unchecked exception:
public class Main {
public static void main(String[] args) {
int[] nums = {1, 2, 3};
System.out.println(nums[3]);
// Throws ArrayIndexOutOfBoundsException
}
}
In this example, the main method attempts to access an element of an array that does not exist. This causes an ArrayIndexOutOfBoundsException exception to be thrown, which is an unchecked exception. Since this is an unchecked exception, it does not need to be handled or declared by the calling method.
In general, checked exceptions should be used to handle expected errors that can be recovered from, while unchecked exceptions should be used to handle unexpected errors that cannot be recovered from.