diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/migration/TryFinallyCanBeTryWithResourcesInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/migration/TryFinallyCanBeTryWithResourcesInspection.java index 1e274fd23ac4..ec893c90d4c3 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/migration/TryFinallyCanBeTryWithResourcesInspection.java +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/migration/TryFinallyCanBeTryWithResourcesInspection.java @@ -315,6 +315,18 @@ public class TryFinallyCanBeTryWithResourcesInspection extends BaseInspection { if (!initializersAreAtTheBeginning(initializerPositions)) return null; Collections.sort(resourceVariables, Comparator.comparing(o -> o.getInitializedElement(), PsiElementOrderComparator.getInstance())); + Optional lastNonTryVar = StreamEx.of(ContainerUtil.reverse(resourceVariables)) + .findFirst(r -> !PsiTreeUtil.isAncestor(tryStatement, r.myVariable, false)); + if (lastNonTryVar.isPresent()) { + PsiVariable variable = lastNonTryVar.get().myVariable; + PsiStatement statement = PsiTreeUtil.getParentOfType(variable, PsiStatement.class); + List statements = collectStatementsBetween(statement, tryStatement); + boolean varUsedNotInTry = StreamEx.of(statements) + .flatMap(stmt -> StreamEx.ofTree((PsiElement)stmt, e -> StreamEx.of(e.getChildren()))) + .select(PsiLocalVariable.class) + .anyMatch(variable1 -> isVariableUsedOutsideContext(variable1, tryStatement)); + if (varUsedNotInTry) return null; + } return new Context(resourceVariables, new HashSet<>(statementsToDelete)); } diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/migration/try_finally_can_be_try_with_resources/TryFinallyCanBeTryWithResources.java b/plugins/InspectionGadgets/test/com/siyeh/igtest/migration/try_finally_can_be_try_with_resources/TryFinallyCanBeTryWithResources.java index 6965d4a60551..e3d710a2d194 100644 --- a/plugins/InspectionGadgets/test/com/siyeh/igtest/migration/try_finally_can_be_try_with_resources/TryFinallyCanBeTryWithResources.java +++ b/plugins/InspectionGadgets/test/com/siyeh/igtest/migration/try_finally_can_be_try_with_resources/TryFinallyCanBeTryWithResources.java @@ -101,4 +101,22 @@ class FinallyContainsTry { } } } +} + +class NonResourceBeforeTry { + public static String test(String str) throws IOException { + final InputStream stream = new ByteArrayInputStream(str.getBytes()); + final StringBuilder res = new StringBuilder(); + try { + int entry; + while ((entry = stream.read()) > -1) { + res.append(entry).append("\n"); + } + } + finally { + stream.close(); + } + + return res.toString(); + } } \ No newline at end of file