Search code examples
c#javatry-catchusing-statementtry-catch-finally

How should I replicate the functionality of C#'s 'using' statement in Java?


I'm converting some C# code to Java and it contains the using statement. How should I replicate this functionality in Java? I was going to use a try, catch, finally block but I thought I'd check with you guys first.


Solution

  • The standard idiom for resource handling in Java is:

    final Resource resource = acquire();
    try {
        use(resource);
    } finally {
        resource.dispose();
    }
    

    Common mistakes include trying to share the same try statement with exception catching and following on from that making a mess with nulls and such.

    The Execute Around Idiom can extract constructs like this, although the Java syntax is verbose.

    executeWith(new Handler() { public void use(Resource resource) {
        ...
    }});