Exception Handling Types in Java

In Java, there are two main types of exceptions: checked exceptions and unchecked exceptions. Additionally, there is also the Error class which represents exceptional conditions that are not recoverable.

Checked Exceptions

Checked exceptions are those that are checked by the Java compiler at compile-time. They represent exceptional conditions that a well-written Java program should anticipate and handle. Examples of checked exceptions include FileNotFoundException, IOException, SQLException, etc. In Java, checked exceptions must be caught or declared in the method signature using the throws keyword.

Here is an example of using a checked exception:

import java.io.*;
public class Example {
  public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new FileReader("file.txt"));
    String line;
    while ((line = br.readLine()) != null) {
      System.out.println(line);
    }
    br.close();
  }
}

In the above example, we are reading a file using a BufferedReader object. The readLine() method can throw an IOException, which is a checked exception. We are handling this exception by declaring it in the method signature using the throws keyword.

Unchecked Exceptions

Unchecked exceptions are those that are not checked by the Java compiler at compile-time. They represent exceptional conditions that cannot be anticipated or handled by a well-written Java program. Examples of unchecked exceptions include NullPointerException, ArrayIndexOutOfBoundsException, etc. In Java, unchecked exceptions do not need to be caught or declared in the method signature.

Here is an example of an unchecked exception:

public class Example {
  public static void main(String[] args) {
    int[] array = new int[5];
    array[7] = 10;
  }
}

In the above example, we are trying to access an array element that is outside the bounds of the array. This will throw an ArrayIndexOutOfBoundsException, which is an unchecked exception.

Errors

Errors are exceptional conditions that are not recoverable. They represent serious problems that cannot be handled by a Java program. Examples of errors include OutOfMemoryError, StackOverflowError, etc. In Java, errors do not need to be caught or declared in the method signature.

Here is an example of an error:

public class Example {
  public static void main(String[] args) {
    throw new StackOverflowError("Stack overflow occurred!");
  }
}

In the above example, we are throwing a StackOverflowError, which is an error that occurs when the stack size of a thread is exceeded.

In summary, Java has three types of exceptions: checked exceptions, unchecked exceptions, and errors. Checked exceptions are checked by the Java compiler at compile-time and must be caught or declared in the method signature using the throws keyword. Unchecked exceptions and errors do not need to be caught or declared in the method signature.