Here says that it is impossible to recover from errors. I am not sure what does it mean because I can catch Error just like Exception. Eg:
public static void main(String args[]) {
while (true) {
try {
throw new StackOverflowError("stackoverflow");
} catch (Throwable throwable) {
//do something
}
//program recover and continue to execute
}
}
The above program execute normally and It seems that It's possible to recover from errors. Can anyone help?
UPDATE:
example of stackoverflow is a little puzzling, only idiot want to recover from stackoverflow. Here is another example about OutOfMemory:
public class Main {
public static Map<Long, Object> cache = null;
public static void main(String args[]){
while(true){
try {
if(cache == null) {
cache = new HashMap<>();
}
for (long i = 0; i < Long.MAX_VALUE; ++i) {
cache.put(i, i);
}
}catch(OutOfMemoryError error) {
cache.clear();//delete some unused entry or clear all.
cache = null;
System.gc();
System.out.println("release memory");
}
}
}
}
It's a simple HashMap cache, execute the code using java -Xmx1m Main
, and we will see an OutOfMemoryError soon, then release memory manually, and the program will continue to execute. insert-> OutOfMemoryError -> release -> insert...
See? the program have recovered from an OutOfMemoryError. Isn't it? And I think it's meaningful. So, Why someone still said program can't recover from OutOfMemoryError.