Can finalize be called after a constructor throws an exception?

前端 未结 3 835
青春惊慌失措
青春惊慌失措 2021-01-01 17:06

Are there any details on whether or not an object is cleaned up using finalize() if that object\'s constructor thew an exception.

When this method is ca

3条回答
  •  春和景丽
    2021-01-01 17:10

    My test shows that it can

    public class Test1 {
    
        Test1() {
            throw new RuntimeException();
        }
    
        @Override
        protected void finalize() throws Throwable {
            System.out.println("finalized");
        }
    
        public static void main(String[] args) throws Exception {
            try {
                new Test1();
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
            System.gc();
            Thread.sleep(1000);
        }
    }
    

    prints

    java.lang.RuntimeException
        at test.Test1.(Test1.java:13)
        at test.Test1.main(Test1.java:24)
    finalized
    

    it is on Java HostSpot Client VM 1.7.0_03

提交回复
热议问题