AddExceptionToExistingCatchFix: hide fix in catch or finally IDEA-189654

This commit is contained in:
Roman.Ivanov
2018-04-06 12:26:55 +07:00
parent 9fe8f989f5
commit b973d42f1c
3 changed files with 54 additions and 0 deletions

View File

@@ -36,6 +36,8 @@ import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import static com.intellij.util.ObjectUtils.tryCast;
public class AddExceptionToExistingCatchFix extends PsiElementBaseIntentionAction {
private final PsiElement myErrorElement;
@@ -179,8 +181,12 @@ public class AddExceptionToExistingCatchFix extends PsiElementBaseIntentionActio
}
List<PsiClassType> unhandledExceptions = new ArrayList<>(ExceptionUtil.getOwnUnhandledExceptions(element));
if (unhandledExceptions.isEmpty()) return null;
boolean containsInCatchOrFinally = containsInCatchOrFinally(element);
List<PsiTryStatement> tryStatements =
PsiTreeUtil.collectParentsOfType(element, PsiTryStatement.class, PsiLambdaExpression.class, PsiClass.class);
if (containsInCatchOrFinally) {
tryStatements.remove(0);
}
List<PsiCatchSection> sections =
tryStatements.stream()
.flatMap(stmt -> Arrays.stream(stmt.getCatchSections()))
@@ -194,6 +200,26 @@ public class AddExceptionToExistingCatchFix extends PsiElementBaseIntentionActio
return new Context(sections, unhandledExceptions);
}
private static boolean containsInCatchOrFinally(@NotNull PsiElement element) {
PsiElement parent = element.getParent();
while (parent != null) {
if (parent instanceof PsiTryStatement) {
return false;
}
if (parent instanceof PsiCatchSection) {
return true;
}
if (parent instanceof PsiCodeBlock) {
PsiKeyword keyword = tryCast(PsiTreeUtil.skipWhitespacesAndCommentsBackward(parent), PsiKeyword.class);
if (keyword != null && keyword.getText().equals(PsiKeyword.FINALLY)) {
return true;
}
}
parent = parent.getParent();
}
return false;
}
private String getMessage() {
if (myCatches.size() == 1 && myExceptions.size() == 1) {
PsiClassType exceptionType = myExceptions.get(0);

View File

@@ -0,0 +1,13 @@
// "Add exception to existing catch clause" "false"
import java.io.File;
class MyException extends Exception {}
class Test {
public static void main(String[] args) {
try {
} catch (RuntimeException e) {
throw new MyException<caret>();
}
}
}

View File

@@ -0,0 +1,15 @@
// "Add exception to existing catch clause" "false"
import java.io.File;
class MyException extends Exception {}
class Test {
public static void main(String[] args) {
try {
} catch (RuntimeException e) {
} finally // comment
{
throw new MyException<caret>();
}
}
}