Sobes.tech
Middle

What are the exceptions in Java? Checked and unchecked.

sobes.tech AI

Answer from AI

In Java, exceptions are divided into two main categories:

  1. Checked exceptions — these are exceptions that are checked by the compiler at compile time. A method that can throw them must declare them in its signature using the throws keyword, and the calling code must handle them either through try-catch or by propagating them further.

    Example: IOException, SQLException.

  2. Unchecked exceptions — these are runtime exceptions that do not require mandatory handling or declaration. They inherit from RuntimeException.

    Example: NullPointerException, IllegalArgumentException.

This division helps explicitly indicate errors that can and should be handled, and errors that usually indicate programming mistakes and do not require mandatory handling.

Example:

public void readFile(String path) throws IOException {
    // Checked exception
    FileReader file = new FileReader(path);
}

public void processData(Object data) {
    if (data == null) {
        throw new NullPointerException("Data cannot be null"); // Unchecked
    }
}