user2898147
user2898147

Reputation:

Will this release my resources after being used?

Will this release my resources after being used?

    InputStream inputStream;
    try (InputStream unverifiedStream = connection.getInputStream()){
        inputStream = unverifiedStream;
    } catch (Exception e) {
        e.printStackTrace();
    }
    //and use stream here to do other stuff with other streams

Upvotes: 1

Views: 118

Answers (3)

fge
fge

Reputation: 121780

Since you are using a try-with-resource statement, and if by "released" you mean "closed" then yes.

Any instance implementing AutoCloseable opened in a try-with-resources statement is .close()d right before catch, so in your case unverifiedStream will be closed before you catch Exception.

It should also be noted that Closeable extends AutoCloseable, so all existing classes implementing Closeable will "magically" work within a try-with-resources statement.

Sample code:

public final class AutoCloseableExample
{
    private static final class Foo
        implements AutoCloseable
    {
        @Override
        public void close()
            throws IOException
        {
            System.out.println("foo");
            throw new IOException();
        }
    }

    public static void main(final String... args)
    {
        try (
            final Foo foo = new Foo();
        ) {
            System.out.println("try block");
        } catch (IOException ignored) {
            System.out.println("exception!");
        } finally {
            System.out.println("finally block");
        }
    }
}

Output:

try block
foo
exception!
finally block

Side note: you should not catch Exception since this also catches all unchecked exceptions (ie, RuntimeException and derivates). Catch more specific exceptions instead.

Upvotes: 1

erickson
erickson

Reputation: 269797

I haven't tried this, but I don't think it will compile if you try to use inputStream after the try-catch block, because inputStream won't be initialized if connection.getInputStream() throws an exception. Your catch block should assign a value or introduce a different flow of control to take care of that possibility.

If the try block completes normally, inputStream will refer to a closed stream outside the try-catch block, and most implementations will throw an exception on any operation you attempt on the stream.

Upvotes: 0

candied_orange
candied_orange

Reputation: 7344

That will release your resources (close the stream) and leave you talking to a closed stream.

The assignment to inputStream does not copy the stream object. It copies the reference to the stream object. You now have two different ways to talk to the same object.

Upvotes: 3

Related Questions