TryFinallyCanBeTryWithResources:remove finally if no stmt: IDEA-CR-28726

This commit is contained in:
Roman Ivanov
2018-01-26 10:59:40 +07:00
parent e926fc71e3
commit 2c40a8a181
5 changed files with 14 additions and 24 deletions
@@ -107,8 +107,14 @@ public class TryFinallyCanBeTryWithResourcesInspection extends BaseInspection {
}
PsiCodeBlock finallyBlock = tryStatement.getFinallyBlock();
if(finallyBlock == null) return;
if(finallyNonEmpty(finallyBlock)) {
if(!ControlFlowUtils.isEmptyCodeBlock(finallyBlock)) {
sb.append("finally").append(finallyBlock.getText());
} else {
PsiElement[] finallyBlockChildren = finallyBlock.getChildren();
if(!StreamEx.of(finallyBlockChildren).skip(1).limit(finallyBlockChildren.length - 2).allMatch(el -> el instanceof PsiWhiteSpace)) {
PsiElement tryParent = tryStatement.getParent();
tryParent.addRangeAfter(finallyBlockChildren[1], finallyBlockChildren[finallyBlockChildren.length - 2], tryStatement);
}
}
tryStatement.replace(JavaPsiFacade.getElementFactory(project).createStatementFromText(sb.toString(), tryStatement));
}
@@ -139,16 +145,6 @@ public class TryFinallyCanBeTryWithResourcesInspection extends BaseInspection {
statement.delete();
}
}
private static boolean finallyNonEmpty(PsiCodeBlock finallyBlock) {
PsiElement[] children = finallyBlock.getChildren();
for (int i = 1; i < children.length - 1; i++) {
if (!(children[i] instanceof PsiWhiteSpace)) {
return true;
}
}
return false;
}
}
@Override
@@ -5,11 +5,9 @@ import java.io.*;
class Comments {
void m(OutputStream out) throws IOException {
try (InputStream in = new FileInputStream("filename")) {
} finally {
// stop
// now
out.close();
try (out; InputStream in = new FileInputStream("filename")) {
}
// stop
// now
}
}
@@ -1,6 +1,3 @@
/*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.siyeh.igfixes.migration.try_finally_can_be_try_with_resources;
import java.io.*;
@@ -8,9 +8,8 @@ class X {
try (Reader r = new FileReader("")) {
r.read();
} finally {
// 1
/*2*/
}
// 1
/*2*/
}
}
@@ -67,8 +67,8 @@ class TryFinallyCanBeTryWithResources {
class Java9 {
void test() throws FileNotFoundException {
PrintStream printStream;
printStream = new PrintStream("");
PrintStream printStream = new PrintStream("");
printStream.print(false);
<warning descr="'try' can use automatic resource management">try</warning> {
printStream.print(true);
} finally {