【问题标题】:runtime error is thrown in the thread "main"在线程“main”中引发运行时错误
【发布时间】:2016-03-06 04:29:53
【问题描述】:

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

}

【问题讨论】:

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


    【解决方案1】:

    它会抛出不扩展异常的 OutOfMemoryError。所以你无法通过异常捕获它。

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

    【讨论】:

      猜你喜欢
      • 2015-04-15
      • 1970-01-01
      • 2021-07-01
      • 2014-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-24
      相关资源
      最近更新 更多