• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Java CatchTree类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中com.sun.source.tree.CatchTree的典型用法代码示例。如果您正苦于以下问题:Java CatchTree类的具体用法?Java CatchTree怎么用?Java CatchTree使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



CatchTree类属于com.sun.source.tree包,在下文中一共展示了CatchTree类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: visitCatch

import com.sun.source.tree.CatchTree; //导入依赖的package包/类
@Override
public Boolean visitCatch(CatchTree tree, Stack<Tree> d) {
    TypeMirror type1 = info.getTrees().getTypeMirror(new TreePath(new TreePath(getCurrentPath(), tree.getParameter()), tree.getParameter().getType()));
    Types t = info.getTypes();
    
    if (type1 != null) {
        Set<TypeMirror> toRemove = new HashSet<TypeMirror>();
        Map<TypeMirror, List<Tree>> exceptions2Highlights = exceptions2HighlightsStack.peek();
        
        if (exceptions2Highlights != null) {
            for (TypeMirror type2 : exceptions2Highlights.keySet()) {
                if (t.isAssignable(type2, type1)) {
                    toRemove.add(type2);
                }
            }
            
            for (TypeMirror type : toRemove) {
                exceptions2Highlights.remove(type);
            }
        }
        
    }
    
    scan(tree.getParameter(), d);
    return scan(tree.getBlock(), d);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:27,代码来源:MethodExitDetector.java


示例2: performRewrite

import com.sun.source.tree.CatchTree; //导入依赖的package包/类
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    TreePath tp = ctx.getPath();
    List<Tree> exceptions = new LinkedList<Tree>();

    for (TypeMirrorHandle<TypeMirror> h : exceptionHandles) {
        TypeMirror tm = h.resolve(wc);

        if (tm == null) return ; //XXX: log

        exceptions.add(wc.getTreeMaker().Type(tm));
    }

    VariableTree excVar = ((CatchTree) tp.getLeaf()).getParameter();

    wc.rewrite(excVar.getType(), wc.getTreeMaker().UnionType(exceptions));
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:19,代码来源:UseSpecificCatch.java


示例3: visitTry

import com.sun.source.tree.CatchTree; //导入依赖的package包/类
@Override
public Void visitTry(TryTree node, Collection<TreePath> trees) {
    Set<TypeMirror> caught = new HashSet<TypeMirror>();

    for (CatchTree ct : node.getCatches()) {
        TypeMirror t = info.getTrees().getTypeMirror(new TreePath(new TreePath(getCurrentPath(), ct), ct.getParameter()));

        if (t != null) {
            caught.add(t);
        }
    }

    caughtExceptions.push(caught);
    
    try {
        scan(node.getBlock(), trees);
    } finally {
        caughtExceptions.pop();
    }
    scan(node.getFinallyBlock(), trees);
    return null;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:23,代码来源:TryCatchFinally.java


示例4: performRewrite

import com.sun.source.tree.CatchTree; //导入依赖的package包/类
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    Tree t = ctx.getPath().getLeaf();
    if (t.getKind() != Tree.Kind.CATCH) {
        // remove a clause from the multi-catch
        removeAlternativeFromMultiCatch(ctx);
        return;
    }
    CatchTree toRemove = (CatchTree)t;
    TryTree parent = (TryTree) ctx.getPath().getParentPath().getLeaf();
    TreeMaker make = ctx.getWorkingCopy().getTreeMaker();
    
    if (parent.getResources().isEmpty() && parent.getCatches().size() == 1) {
        List<StatementTree> repl = new ArrayList<>();
        repl.addAll(parent.getBlock().getStatements());
        if (parent.getFinallyBlock() != null) {
                repl.addAll(parent.getFinallyBlock().getStatements());
        }
        Utilities.replaceStatement(ctx.getWorkingCopy(), ctx.getPath().getParentPath(), repl);
    } else {
        ctx.getWorkingCopy().rewrite(parent, make.removeTryCatch(parent, toRemove));
    }
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:24,代码来源:ExtraCatch.java


示例5: createCatch

import com.sun.source.tree.CatchTree; //导入依赖的package包/类
private static CatchTree createCatch(WorkingCopy info, TreeMaker make, TreePath statement, String name, TypeMirror type) {
    StatementTree logStatement = createExceptionsStatement(info, make, name);

    if (logStatement == null) {
        logStatement = createLogStatement(info, make, statement, name);
    }
    
    if (logStatement == null) {
        logStatement = createRethrowAsRuntimeExceptionStatement(info, make, name);
    }
    
    if (logStatement == null) {
        logStatement = createRethrow(info, make, name);
    }

    if (logStatement == null) {
        logStatement = createPrintStackTraceStatement(info, make, name);
    }

    return make.Catch(make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), name, make.Type(type), null), make.Block(Collections.singletonList(logStatement), false));
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:22,代码来源:MagicSurroundWithTryCatchFix.java


示例6: visitTry

import com.sun.source.tree.CatchTree; //导入依赖的package包/类
@Override
public Boolean visitTry(TryTree node, Void p) {
    Set<TypeMirror> caught = new HashSet<TypeMirror>();

    for (CatchTree ct : node.getCatches()) {
        TypeMirror t = info.getTrees().getTypeMirror(new TreePath(new TreePath(getCurrentPath(), ct), ct.getParameter()));

        if (t != null) {
            caught.add(t);
        }
    }

    caughtExceptions.push(Pair.of(caught, node));
    
    try {
        return scan(node.getBlock(), p) == Boolean.TRUE || scan(node.getFinallyBlock(), p) == Boolean.TRUE;
    } finally {
        caughtExceptions.pop();
    }
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:21,代码来源:Utilities.java


示例7: assignmentToCatchBlockParameter

import com.sun.source.tree.CatchTree; //导入依赖的package包/类
@Hint(displayName = "#DN_org.netbeans.modules.java.hints.AssignmentIssues.assignmentToCatchBlockParameter", description = "#DESC_org.netbeans.modules.java.hints.AssignmentIssues.assignmentToCatchBlockParameter", category = "assignment_issues", enabled = false, suppressWarnings = "AssignmentToCatchBlockParameter", options=Options.QUERY) //NOI18N
@TriggerTreeKind(Kind.CATCH)
public static List<ErrorDescription> assignmentToCatchBlockParameter(HintContext context) {
    final Trees trees = context.getInfo().getTrees();
    final TreePath catchPath = context.getPath();
    final Element param = trees.getElement(TreePath.getPath(catchPath, ((CatchTree) catchPath.getLeaf()).getParameter()));
    if (param == null || param.getKind() != ElementKind.EXCEPTION_PARAMETER) {
        return null;
    }
    final TreePath block = TreePath.getPath(catchPath, ((CatchTree) catchPath.getLeaf()).getBlock());
    final List<TreePath> paths = new LinkedList<TreePath>();
    new AssignmentFinder(trees, param).scan(block, paths);
    final List<ErrorDescription> ret = new ArrayList<ErrorDescription>(paths.size());
    for (TreePath path : paths) {
        ret.add(ErrorDescriptionFactory.forTree(context, path, NbBundle.getMessage(AssignmentIssues.class, "MSG_AssignmentToCatchBlockParameter", param.getSimpleName()))); //NOI18N
    }
    return ret;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:19,代码来源:AssignmentIssues.java


示例8: visitCatchClause

import com.sun.source.tree.CatchTree; //导入依赖的package包/类
/**
 * Helper method for {@link CatchTree}s.
 */
private void visitCatchClause(CatchTree node, AllowTrailingBlankLine allowTrailingBlankLine) {
    sync(node);
    builder.space();
    token("catch");
    builder.space();
    token("(");
    builder.open(plusFour);
    VariableTree ex = node.getParameter();
    if (ex.getType().getKind() == UNION_TYPE) {
        builder.open(ZERO);
        visitUnionType(ex);
        builder.close();
    } else {
        // TODO(cushon): don't break after here for consistency with for, while, etc.
        builder.breakToFill();
        builder.open(ZERO);
        scan(ex, null);
        builder.close();
    }
    builder.close();
    token(")");
    builder.space();
    visitBlock(
            node.getBlock(), CollapseEmptyOrNot.NO, AllowLeadingBlankLine.YES, allowTrailingBlankLine);
}
 
开发者ID:tranleduy2000,项目名称:javaide,代码行数:29,代码来源:JavaInputAstVisitor.java


示例9: visitCatch

import com.sun.source.tree.CatchTree; //导入依赖的package包/类
@Override
public Void visitCatch(CatchTree node, Void p) {
    TreePath param = new TreePath(getCurrentPath(), node.getParameter());
    Element ex = trees.getElement(param);
    validateUnionTypeInfo(ex);
    if (ex.getSimpleName().contentEquals("ex")) {
        assertTrue(ex.getKind() == ElementKind.EXCEPTION_PARAMETER, "Expected EXCEPTION_PARAMETER - found " + ex.getKind());
        for (Element e : types.asElement(trees.getLub(node)).getEnclosedElements()) {
            Member m = e.getAnnotation(Member.class);
            if (m != null) {
                assertTrue(e.getKind() == m.value(), "Expected " + m.value() + " - found " + e.getKind());
            }
        }
        assertTrue(assertionCount == 9, "Expected 9 assertions - found " + assertionCount);
    }
    return super.visitCatch(node, p);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:18,代码来源:ModelChecker.java


示例10: visitTry

import com.sun.source.tree.CatchTree; //导入依赖的package包/类
@Override
public Void visitTry(TryTree tryTree, List<ReformatOption> optionsToReformat) {
    addLeftBraceToList(optionsToReformat, tryTree.getBlock(), PreferencesFormatOptions.BRACES_IN_OTHER_DECLARATION);
    BlockTree finalBlock = tryTree.getFinallyBlock();
    List<? extends CatchTree> catches = tryTree.getCatches();

    if (finalBlock instanceof CompoundTree) {
        addLeftBraceToList(optionsToReformat, finalBlock, PreferencesFormatOptions.BRACES_IN_OTHER_DECLARATION);
        addRightBraceToList(optionsToReformat, (CompoundTree) finalBlock, PreferencesFormatOptions.AFTER_OTHER_DECLARATION);
    } else if (!catches.isEmpty()) {
        BlockTree catchBlock = catches.get(catches.size() - 1).getBlock();
        addRightBraceToList(optionsToReformat, (CompoundTree) catchBlock, PreferencesFormatOptions.AFTER_OTHER_DECLARATION);
    } else {
        addRightBraceToList(optionsToReformat, (CompoundTree) tryTree.getBlock(), PreferencesFormatOptions.AFTER_OTHER_DECLARATION);
    }

    return null;
}
 
开发者ID:fundacionjala,项目名称:oblivion-netbeans-plugin,代码行数:19,代码来源:ReformatTreeVisitor.java


示例11: testVisitCatch

import com.sun.source.tree.CatchTree; //导入依赖的package包/类
@Test
public void testVisitCatch() throws ParseException, BadLocationException, IOException {
    List<ReformatOption> optionsToReformat = new ArrayList<>();
    CompilationUnitTree unit = getCompilationUnitTree(INPUT_FILE);
    MethodTree methodTree = TreeNavigationUtils.findMethodTreeByName("doSomething", unit).get(0);
    TryTree tryTree = (TryTree) getStatementTreeByClassName(TryTree.class, methodTree);

    if (tryTree == null) {
        fail(ERROR_MESSAGE);
    }

    CatchTree catchTree = tryTree.getCatches().get(0);

    ReformatTreeVisitor reformatTreeVisitor = getReformatTreeVisitor(INPUT_FILE);
    reformatTreeVisitor.visitCatch(catchTree, optionsToReformat);

    assertFalse(optionsToReformat.isEmpty());
}
 
开发者ID:fundacionjala,项目名称:oblivion-netbeans-plugin,代码行数:19,代码来源:ReformatTreeVisitorTest.java


示例12: testVisitCatchNotReformat

import com.sun.source.tree.CatchTree; //导入依赖的package包/类
@Test
public void testVisitCatchNotReformat() throws ParseException, BadLocationException, IOException {
    List<ReformatOption> optionsToReformat = new ArrayList<>();
    CompilationUnitTree unit = getCompilationUnitTree(INPUT_FILE);
    MethodTree methodTree = TreeNavigationUtils.findMethodTreeByName("doSomething", unit).get(0);
    TryTree tryTree = (TryTree) getStatementTreeByClassName(TryTree.class, methodTree);

    if (tryTree == null) {
        fail(ERROR_MESSAGE);
    }

    CatchTree catchTree = tryTree.getCatches().get(0);

    ReformatTreeVisitor reformatTreeVisitor = getReformatTreeVisitor(INPUT_FILE, 10, 20);
    reformatTreeVisitor.visitCatch(catchTree, optionsToReformat);

    assertTrue(optionsToReformat.isEmpty());
}
 
开发者ID:fundacionjala,项目名称:oblivion-netbeans-plugin,代码行数:19,代码来源:ReformatTreeVisitorTest.java


示例13: matchTry

import com.sun.source.tree.CatchTree; //导入依赖的package包/类
@Override
public Description matchTry(TryTree tree, VisitorState state) {
  if (tree.getCatches().isEmpty()) {
    return NO_MATCH;
  }
  // Find catch blocks that contain only a call to fail, and that ignore the caught exception.
  ImmutableList<CatchTree> catchBlocks =
      tree.getCatches()
          .stream()
          .filter(
              c ->
                  c.getBlock().getStatements().size() == 1
                      && FAIL_METHOD.matches(getOnlyElement(c.getBlock().getStatements()), state))
          .filter(c -> !catchVariableIsUsed(c))
          .collect(toImmutableList());
  if (catchBlocks.isEmpty()) {
    return NO_MATCH;
  }
  Description.Builder description = buildDescription(tree);
  rethrowFix(catchBlocks, state).ifPresent(description::addFix);
  deleteFix(tree, catchBlocks, state).ifPresent(description::addFix);
  return description.build();
}
 
开发者ID:google,项目名称:error-prone,代码行数:24,代码来源:CatchFail.java


示例14: rethrowFix

import com.sun.source.tree.CatchTree; //导入依赖的package包/类
private Optional<Fix> rethrowFix(ImmutableList<CatchTree> catchBlocks, VisitorState state) {
  SuggestedFix.Builder fix = SuggestedFix.builder();
  catchBlocks.forEach(
      c -> {
        // e.g.
        // fail("message") -> throw new AssertionError("message", cause);
        // assertWithMessage("message format %s", 42) ->
        //     throw new AssertionError(String.format("message format %s", 42), cause);
        StatementTree statementTree = getOnlyElement(c.getBlock().getStatements());
        MethodInvocationTree methodInvocationTree =
            (MethodInvocationTree) ((ExpressionStatementTree) statementTree).getExpression();
        String message = null;
        if (message == null && !methodInvocationTree.getArguments().isEmpty()) {
          message = getMessageOrFormat(methodInvocationTree, state);
        }
        if (message != null) {
          // only catch and rethrow to add additional context, not for raw `fail()` calls
          fix.replace(
              statementTree,
              String.format(
                  "throw new AssertionError(%s, %s);", message, c.getParameter().getName()));
        }
      });
  return fix.isEmpty() ? Optional.empty() : Optional.of(fix.build());
}
 
开发者ID:google,项目名称:error-prone,代码行数:26,代码来源:CatchFail.java


示例15: catchVariableIsUsed

import com.sun.source.tree.CatchTree; //导入依赖的package包/类
private boolean catchVariableIsUsed(CatchTree c) {
  VarSymbol sym = ASTHelpers.getSymbol(c.getParameter());
  boolean[] found = {false};
  c.getBlock()
      .accept(
          new TreeScanner<Void, Void>() {
            @Override
            public Void visitIdentifier(IdentifierTree node, Void aVoid) {
              if (Objects.equals(sym, ASTHelpers.getSymbol(node))) {
                found[0] = true;
              }
              return super.visitIdentifier(node, aVoid);
            }
          },
          null);
  return found[0];
}
 
开发者ID:google,项目名称:error-prone,代码行数:18,代码来源:CatchFail.java


示例16: tryCatchesException

import com.sun.source.tree.CatchTree; //导入依赖的package包/类
/** Return whether the given try-tree will catch the given exception type. */
private boolean tryCatchesException(TryTree tryTree, Type exceptionToCatch, VisitorState state) {
  Types types = state.getTypes();
  return tryTree
      .getCatches()
      .stream()
      .anyMatch(
          (CatchTree catchClause) -> {
            Type catchesException = getType(catchClause.getParameter().getType());
            // Examine all alternative types of a union type.
            if (catchesException != null && catchesException.isUnion()) {
              return Streams.stream(((UnionClassType) catchesException).getAlternativeTypes())
                  .anyMatch(caught -> types.isSuperType(caught, exceptionToCatch));
            }
            // Simple type, just check superclass.
            return types.isSuperType(catchesException, exceptionToCatch);
          });
}
 
开发者ID:google,项目名称:error-prone,代码行数:19,代码来源:WakelockReleasedDangerously.java


示例17: matchTry

import com.sun.source.tree.CatchTree; //导入依赖的package包/类
@Override
public Description matchTry (TryTree tree, VisitorState state) {
  List<? extends CatchTree> catchList = tree.getCatches();
  if (catchList == null || catchList.size() == 0) {
    // TODO: this try block does not have a catch, we should further check the 
    // finally block!
    return Description.NO_MATCH;
  }
 
  CatchTree lastCatch = catchList.get(tree.getCatches().size() - 1);
  if (overcatch(lastCatch, state)) {
    if (abortInCatch(lastCatch, state)) {
      LineMap lineMap = state.getPath().getCompilationUnit().getLineMap();

      /* System.out.println("****** warning starts **************");
        System.out.println("WARNING: abort in overcatch: " 
           + state.getPath().getCompilationUnit().getSourceFile().getName()
           + ":" + lineMap.getLineNumber(TreeInfo.getStartPos((JCTree) lastCatch)));
        System.out.println(state.getPath().getLeaf());
          System.out.println("****** warning ends **************");
        System.out.println();  */
      return describeMatch(lastCatch, NO_FIX);
    }
  }
  return Description.NO_MATCH;
}
 
开发者ID:diy1,项目名称:error-prone-aspirator,代码行数:27,代码来源:AbortInOvercatch.java


示例18: abortInCatch

import com.sun.source.tree.CatchTree; //导入依赖的package包/类
private boolean abortInCatch(CatchTree catchTree, VisitorState state) {
  List<? extends StatementTree> statements = catchTree.getBlock().getStatements();
  if (statements.isEmpty()) {
    return false;
  }
  StatementTree lastStmt = statements.get(statements.size() - 1);
  if (lastStmt.getKind() == EXPRESSION_STATEMENT) {
    ExpressionTree et = ((ExpressionStatementTree) lastStmt).getExpression();

    Symbol sym = ASTHelpers.getSymbol(et);
    if (sym == null || !(sym instanceof MethodSymbol)) {
      return false;
    }

    String methodName = sym.getQualifiedName().toString();
    String className = sym.owner.getQualifiedName().toString();

    // System.out.println("DEBUG: method: " + methodName + ", className: " + className);
    if (methodName.contains("abort") || 
           methodName.contains("shutdown") ||
           (methodName.equals("exit") && className.equals("java.lang.System"))) {
      return true;
    }
  }
  return false;
}
 
开发者ID:diy1,项目名称:error-prone-aspirator,代码行数:27,代码来源:AbortInOvercatch.java


示例19: matchTry

import com.sun.source.tree.CatchTree; //导入依赖的package包/类
@Override
public Description matchTry (TryTree tree, VisitorState state) {
  if (badEmptyCatchBlock(tree, state)) {
    // If it has finally block, assume it's OK
    BlockTree bt = tree.getFinallyBlock();
    if (bt == null || bt.getStatements().size() == 0) {
      CatchTree lastCatch = tree.getCatches().get(tree.getCatches().size() - 1);
      LineMap lineMap = state.getPath().getCompilationUnit().getLineMap();

       /* System.out.println("****** warning starts **************");
        System.out.println("WARNING: empty catch: " 
           + state.getPath().getCompilationUnit().getSourceFile().getName()
           // + ":" + state.getEndPosition((JCTree) tree)
           + ":" + lineMap.getLineNumber(TreeInfo.getStartPos((JCTree) lastCatch)));
        System.out.println(state.getPath().getLeaf());
        System.out.println(); 
        System.out.println("****** warning ends **************"); */

      return describeMatch(lastCatch, NO_FIX);
    }
  }
  return Description.NO_MATCH;
}
 
开发者ID:diy1,项目名称:error-prone-aspirator,代码行数:24,代码来源:EmptyCatch.java


示例20: exceptionWhitelisted

import com.sun.source.tree.CatchTree; //导入依赖的package包/类
private boolean exceptionWhitelisted (CatchTree catchTree, VisitorState state) {
  /* We further check the exception type, and ignore these exceptions. */
  String caughtException = catchTree.getParameter().toString();
  boolean canBeIgnored = false;
  for (String harmlessExp : harmlessExceptions) {
    if (caughtException.contains(harmlessExp)) {
      canBeIgnored = true;
      break;
    }
  }
  if (canBeIgnored) {
    // System.out.println("DEBUG: found empty handler for an harmless exception: " + caughtException);
    return true;
  }
  // System.out.println("DEBUG: catchType = " + caughtException);
  return false;
}
 
开发者ID:diy1,项目名称:error-prone-aspirator,代码行数:18,代码来源:EmptyCatch.java



注:本文中的com.sun.source.tree.CatchTree类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java Globals类代码示例发布时间:2022-05-21
下一篇:
Java FillRect类代码示例发布时间:2022-05-21
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap