Sobes.tech
Middle

What type of exception in Java cannot be handled?

sobes.tech AI

Answer from AI

Error.

Java separates exceptions (Throwable) into three main types:

  1. Checked Exceptions: Require mandatory handling or declaration in the method signature (throws).
  2. Unchecked Exceptions (Runtime Exceptions): Do not require mandatory handling. Usually indicate errors in program logic.
  3. Errors: Represent serious problems related to the Java Virtual Machine or system resources. They cannot be handled at the application level because they are not issues of the code itself.

Examples of Error:

  • OutOfMemoryError: The Java Virtual Machine could not allocate memory.
  • StackOverflowError: Stack overflow occurred (excessively deep recursion).
  • InternalError: Internal error of the Java Virtual Machine.

Handling Error with try-catch is meaningless because these errors indicate states from which the application generally cannot recover successfully. Instead, when an Error occurs, the application usually terminates.

Although technically you can write catch (Error e), such code is considered bad practice and does not solve the main problem.

try {
    // Code that may cause OutOfMemoryError
    List<Object> list = new ArrayList<>();
    while (true) {
        list.add(new Object());
    }
} catch (OutOfMemoryError e) {
    // This block will execute, but you cannot recover,
    // as the system has insufficient memory.
    System.err.println("Out of memory! Application will likely terminate.");
    // Further actions here are useless or will cause SecurityException
} catch (Exception e) {
    // Handling other exceptions
    e.printStackTrace();
}

In QA automation, if an Error occurs during test execution, it more likely indicates a problem with the test environment, incorrect JVM configuration, or a serious defect in the application itself that led to a critical failure, rather than an expected handleable exception. Such scenarios require investigation of the root cause outside the test code.