[Java. Inspections] Refactoring try-with-resources + fix check in AutoCloseableVariableUsedVisitor

IDEA-359576

GitOrigin-RevId: 370c13b9667b0978d7bf95cb6a6fca060a8d368b
This commit is contained in:
Georgii Ustinov
2025-01-23 10:10:57 +00:00
committed by intellij-monorepo-bot
parent 2911de7fee
commit f77b48750b
2 changed files with 29 additions and 3 deletions
@@ -514,7 +514,7 @@ public final class TryFinallyCanBeTryWithResourcesInspection extends BaseInspect
}
private static boolean isAutoCloseableDeclaredInFinallyBlock(@NotNull PsiCodeBlock block, @NotNull PsiVariable variable) {
return variable instanceof PsiLocalVariable && PsiTreeUtil.getParentOfType(variable, PsiCodeBlock.class, true) == block;
return variable instanceof PsiLocalVariable && PsiTreeUtil.isAncestor(block, variable, true);
}
private static @Nullable PsiVariable findAutoCloseableVariable(@Nullable PsiStatement statement) {
@@ -616,8 +616,8 @@ public final class TryFinallyCanBeTryWithResourcesInspection extends BaseInspect
used = true;
return;
}
PsiElement parent = referenceExpression.getParent();
if ((parent instanceof PsiMethodCallExpression && !isCloseMethodCalled(referenceExpression)) || parent instanceof PsiExpressionList) {
PsiElement parent = PsiTreeUtil.getParentOfType(referenceExpression, true, PsiMethodCallExpression.class, PsiExpressionList.class);
if (parent instanceof PsiMethodCallExpression && !isCloseMethodCalled(referenceExpression) || parent instanceof PsiExpressionList) {
used = true;
}
}
@@ -360,6 +360,16 @@ class ExtraUsageOfAutoCloseableInFinally {
}
}
}
public void expressionList() throws Exception {
MyAutoCloseable first = create();
try {
System.out.println(first.hashCode());
} finally {
first.close();
System.out.println(first.hashCode());
}
}
}
class NestedCatchSections {
@@ -480,6 +490,22 @@ class NestedCatchSections {
}
}
}
void variableUsedInSecondInnerTry(InputStream stream) {
try {
System.out.println(1);
} finally {
try {
stream.close();
}
catch (Exception e) {
}
try {
stream.close();
} catch (Exception e) {
}
}
}
}
class UsageOfDependentVariablesInFinally {