我无法捕获异常,而是在主方法中引发了运行时错误。
知道吗?
以下代码:
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");
}
}
它将抛出OutOfMemoryError,而OutOfMemory Error不扩展Exception。因此,您无法通过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");
}