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

前端 未结 5 700
清酒与你
清酒与你 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:09

    Not every Java class (!) throws an exception. Sometimes you just want to use a try-with-resources to use the auto-close feature, and nothing else.

    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }
    

    This the catch is optional because readLine() doesn't throw a (checked) exception.

    Yes, close() could throw an exception, but the try-with-resources handles that too.

    try (BufferedReader br = new BufferedReader(new FileReader(path))) {
        return br.readLine();
    } 
    

    So this try-with-resources doesn't need a catch.

    0 讨论(0)
  • 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()" );
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-02 09:25

    You could check the JLS but there is actually a relatively easy reasoning why this is the only correct way the language should behave.

    The main rule of checked exceptions is that any checked exception declared by a method must be handled, either by catching it or letting the calling method throw it.

    The try-with-resources always (implicitly) calls the close method.

    So if the specific close method of the AutoClosable you use (determined by the type declared in try) declares to throw a checked exception such as a SQLException you do need to handle this checked exception somewhere, otherwise it would be possible to violate the rule!

    If the close method does not declare that it throws a checked exception, the rule is not violated and you do not need to handle a checked exception for implicitly calling the close method. It is actually a compilation failure if you do try to catch a checked exception that is never declared to be thrown.

    0 讨论(0)
  • 2021-02-02 09:26

    It is optional if close() is not able to throw a checked exception. However, if close() can, then a checked exception would need to handled in a normal fashion, either with a catch block, or by throwing from the method that try-with-resources block is in.

    More details are in JLS 14.2.3

    14.20.3.2. Extended try-with-resources

    A try-with-resources statement with at least one catch clause and/or a finally clause is called an extended try-with-resources statement.

    The meaning of an extended try-with-resources statement:

    try ResourceSpecification
        Block
    [Catches]
    [Finally]
    

    is given by the following translation to a basic try-with-resources statement nested inside a try-catch or try-finally or try-catch-finally statement:

    try {
        try ResourceSpecification
           Block
    }
    [Catches]
    [Finally]
    

    The effect of the translation is to put the resource specification "inside" the try statement. This allows a catch clause of an extended try-with-resources statement to catch an exception due to the automatic initialization or closing of any resource.

    Furthermore, all resources will have been closed (or attempted to be closed) by the time the finally block is executed, in keeping with the intent of the finally keyword.

    Thoughts on whether or not this is related to the use of a JNDI DataSource?

    Yes, it is.

    In the example try-with-resourses block you've provided, it is necessary to catch the exception and handle, or throw from the method the block is in, because SQLException is a checked exception.

    0 讨论(0)
  • 2021-02-02 09:28

    You could just be throwing the exception up (or catching it in another try-catch block):

    private static void test() throws IOException {
        try(InputStream is = new FileInputStream("test.txt")) {
            while(is.read() > -1) {
            }
        } finally {
            // Will get executed, even if exception occurs
            System.out.println("Finished");
        }
    }
    
    0 讨论(0)
提交回复
热议问题