Middle
Give an example of an error that occurs at the JVM level.
sobes.tech AI
Answer from AI
For example, OutOfMemoryError. This is a critical error that occurs when the JVM cannot allocate an object due to insufficient memory in the heap, and the garbage collector cannot free enough space.
// Example code that may cause OutOfMemoryError
import java.util.ArrayList;
import java.util.List;
public class MemoryErrorExample {
public static void main(String[] args) {
List<Object> list = new ArrayList<>();
try {
while (true) {
list.add(new Object()); // Continuously add objects until memory runs out
}
} catch (OutOfMemoryError e) {
System.err.println("A critical error occurred: OutOfMemoryError");
e.printStackTrace(); // Print the error stack trace
}
System.out.println("Program terminated."); // This line probably won't be reached
}
}