Why is try-with-resources catch block selectively optional?

前端 未结 5 795
清酒与你
清酒与你 2021-02-02 08:43

I read that the catch block in try-with-resources is optional. I\'ve tried creating a Connection object in a try-with-resources block, with no subsequ

5条回答
  •  南旧
    南旧 (楼主)
    2021-02-02 09:15

    You can create an AutoClosable that does not require an explicit catch-block by declaring your AutoClosable's close() method without any Exception or with a RuntimeException. Without any Exception it is clear that no catch-block is required. Further, the compiler does not statically check for a RuntimeException to be catched (in contrast to checked Exceptions).

    Example:

    public class AutoClosableDemo
    {
    
        public static void main( final String[] args )
        {
            try (MyAutoCloseable1 mac1 = new MyAutoCloseable1())
            {
                System.out.println( "try-with-resource MyAutoCloseable1" );
            }
            try (MyAutoCloseable2 mac2 = new MyAutoCloseable2())
            {
                System.out.println( "try-with-resource MyAutoCloseable2" );
            }
            // The following is not allowed, because
            // "Unhandled exception type Exception thrown by automatic close() invocation on mac3"
            // try (MyAutoCloseable3 mac3 = new MyAutoCloseable3())
            // {
            // System.out.println( "try-with-resource MyAutoCloseable13" );
            // }
            System.out.println( "done" );
        }
    
        public static class MyAutoCloseable1 implements AutoCloseable
        {
            @Override
            public void close()
            {
                System.out.println( "MyAutoCloseable1.close()" );
            }
        }
    
        public static class MyAutoCloseable2 implements AutoCloseable
        {
            @Override
            public void close() throws RuntimeException
            {
                System.out.println( "MyAutoCloseable2.close()" );
            }
        }
    
        public static class MyAutoCloseable3 implements AutoCloseable
        {
            @Override
            public void close() throws Exception
            {
                System.out.println( "MyAutoCloseable3.close()" );
            }
        }
    }
    

提交回复
热议问题