我无法捕获异常,而是在main方法中抛出运行时错误。
有什么想法吗?
以下代码:
public class Test {
public static void main(String[] args) {
ArrayList myList = new ArrayList();
String[] myArray;
try{
while(true){
myList.add("My String");
}
}catch(RuntimeException re){
System.out.println("Caught a RuntimeException");
}catch(Exception re){
System.out.println("Caught a Exception");
}
System.out.println("Ready to use");
}
}
答案 0 :(得分:2)
它将抛出不扩展Exception的OutOfMemoryError。所以你无法通过Exception捕获它。
public static void main(String[] args) {
ArrayList myList = new ArrayList();
try{
while(true){
myList.add("My String");
}
}catch(RuntimeException re){
System.out.println("Caught a RuntimeException");
}catch(Exception re){
System.out.println("Caught a Exception");
} catch (OutOfMemoryError e){
System.out.println("Out of memory");
}
System.out.println("Ready to use");
}