线程“main”中抛出运行时错误

时间:2015-12-02 03:01:26

标签: exception exception-handling java-8 try-catch main

我无法捕获异常,而是在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");
    }

}

1 个答案:

答案 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");
}