Daniel A. White
Daniel A. White

Reputation: 190952

Taking the nusances out of AutoCloseable

Up front: I'm a C# guy doing Java right now. Some of these frustrations come from my lack of knowledge of Java.

First, is there a way to have a "safe" AutoCloseable implementation that does not require the Exception to be checked? If I'm implmementing my own class that won't throw from its close method, I don't see why I have to check it.

Second, is there a way to simplify the expression in the try statement where I don't care what's returned? For instance in C# I can do this:

using (new Disposable()) 
{
    // yay!
}

and Java seems to force me to assign it to a temporary variable:

try (AutoCloseable iDontCare = getAutoCloseable()) {
    // dont you dare use iDontCare
}

I wish I could simplify the Java to

try (getAutoCloseable()) {
    // yay!
}

Upvotes: 1

Views: 2185

Answers (3)

lucasvw
lucasvw

Reputation: 1557

Makoto's answer does a nice job of addressing the first part of your question, so I'll attempt to address the second.

I think what you want is a try (without resources). For example:

try {
    //yay!
} finally {
   // always executed
}

The finally block will execute regardless of whether an exception is thrown or not.

Edit: If you don't need anything to execute, you could just declare a new block

{
    //yay!
}

Upvotes: 0

Juan C Nuno
Juan C Nuno

Reputation: 553

Your first question:

Yes. You can implement AutoCloseable.close without the throws Exception part if your implementation doesn't throw checked exceptions.

Your second question:

No. The try with resources statement requires that variable. You can rename it to something like ignored or unused to make that clear.

final class Test implements AutoCloseable {
    @Override
    public void close() {
        System.out.println("Closing");
    }

    public static void main(String[] args) {
        try (Test ignored = new Test()) {
            System.out.println("Not using ignored");
        }
    }
}

Upvotes: 3

Makoto
Makoto

Reputation: 106450

C# isn't quite Java; this is one of those gotchas you'll have to deal with going forward.

First, is there a way to have a "safe" AutoCloseable implementation that does not require the Exception to be checked? If I'm implmementing my own class that won't throw from its close method, I don't see why I have to check it.

You have to because it's mandated by the interface. Not just that, but it throws a checked exception, which does have to be handled at some level.

If you know for a fact that your code will never throw any kind of exception, you could still place the throwing of the exception in some kind of guaranteed-not-to-be-executed-block inside of your implemented close method. Or, implement your own interface which extends AutoCloseable and overrides close to not throw an exception.

Upvotes: 3

Related Questions