Search code examples
javaintellij-idea

In IntelliJ IDEA, how to surround with try-with-resources?


In IntelliJ IDEA, I can press the "Surround with" shortcut CTRL-ALT-T to surround a block of code with a try / catch block, among other things.

I would like to surround the resource part into a try-with-resources block:

Writer out = Files.newBufferedWriter(destination, StandardCharsets.UTF_8);
temp.process(model, out);

To this:

try (Writer out = Files.newBufferedWriter(destination, StandardCharsets.UTF_8)) {
    temp.process(model, out);
}

However, this option is not available when pressing CTRL-ALT-T.

How can I surround a block of code with a try-with-resources block?


Solution

  • Press ALT-ENTER on any expression representing an AutoCloseable.

    "Surround with try-with-resources block" is an Intention action. It is not an option available in the "Surround with" menu.

    try with resources screenshot