TextRange (Project project, PsiElement container, PsiElement[] statements) { PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project); statements = SurroundWithUtil.moveDeclarationsOut(container, statements, true); if (statements.length == 0) { return null; } List<PsiClassType> exceptions = ExceptionUtil.getUnhandledExceptions(statements); if (exceptions.isEmpty()) { exceptions = ExceptionUtil.getThrownExceptions(statements); if (exceptions.isEmpty()) { exceptions = Collections.singletonList(factory.createTypeByFQClassName("java.lang.Exception", container.getResolveScope())); } } @NonNls StringBuilder buffer = new StringBuilder(); buffer.append("try{\n}"); for (PsiClassType ignored : exceptions) { buffer.append("catch(Exception e){\n}"); } if (myGenerateFinally) { buffer.append("finally{\n}"); } String text = buffer.toString(); PsiTryStatement tryStatement = (PsiTryStatement)factory.createStatementFromText(text, null); tryStatement = (PsiTryStatement)CodeStyleManager.getInstance(project).reformat(tryStatement); tryStatement = (PsiTryStatement)addAfter(tryStatement, container, statements); PsiCodeBlock tryBlock = tryStatement.getTryBlock(); SurroundWithUtil.indentCommentIfNecessary(tryBlock, statements); addRangeWithinContainer(tryBlock, container, statements, true); PsiCatchSection[] catchSections = tryStatement.getCatchSections(); for (int i = 0; i < exceptions.size(); i++) { PsiClassType exception = exceptions.get(i); PsiClass target = exception.resolve(); if (target instanceof PsiTypeParameter) { PsiClassType[] extendsListTypes = target.getExtendsListTypes(); if (extendsListTypes.length > 0) { exception = extendsListTypes[0]; } } String name = new VariableNameGenerator(tryBlock, VariableKind.PARAMETER).byName("e", "ex", "exc").byType(exception).generate(false); PsiCatchSection catchSection = factory.createCatchSection(exception, name, tryBlock); catchSection = (PsiCatchSection)catchSections[i].replace(catchSection); codeStyleManager.shortenClassReferences(catchSection); } container.deleteChildRange(statements[0], statements[statements.length - 1]); PsiCodeBlock firstCatch = tryStatement.getCatchBlocks()[0]; return SurroundWithUtil.getRangeToSelect(firstCatch); }