Sobes.tech
Junior — Middle

Can you list the types of exceptions used in Java and explain their differences?

sobes.tech AI

Answer from AI

In Java, exceptions are divided into two main categories:

  1. Checked Exceptions

    • Inherit from the class Exception, but not from RuntimeException.
    • The compiler requires these exceptions to be either caught in a try-catch block or declared in the method's throws clause.
    • Used for situations that can be anticipated and handled, such as input-output errors (IOException).
  2. Unchecked Exceptions

    • Inherit from RuntimeException.
    • The compiler does not require mandatory handling or declaration.
    • Usually indicate programming errors, such as NullPointerException, IllegalArgumentException.
  3. Errors

    • Inherit from the class Error.
    • Represent serious problems that are usually not handled by the application, such as OutOfMemoryError.

Differences:

  • Checked exceptions require explicit handling, which helps in writing more reliable code.
  • Unchecked exceptions are usually related to programming errors and do not require mandatory handling.
  • Errors indicate problems at the JVM level and are generally not handled.

Example:

try {
    FileReader file = new FileReader("file.txt"); // IOException - checked exception
} catch (IOException e) {
    e.printStackTrace();
}

int a = 5 / 0; // ArithmeticException - unchecked exception