Surround node statement with a try/except block to catch errors.

        This method is called for every node of the parsed code, and only
        changes statement lines.

        Args:
            node (ast.AST): node statement to surround.
426682
def generic_visit(self, node):
        
        if (isinstance(node, ast.stmt) and
                not isinstance(node, ast.FunctionDef)):

            new_node = self.wrap_with_try(node)

            # handling try except statement
            if isinstance(node, self.ast_try_except):
                self.try_except_handler(node)
                return new_node

            # Run recursively on all sub nodes
            super(ErrorsCatchTransformer, self).generic_visit(node)

            return new_node

        # Run recursively on all sub nodes
        return super(ErrorsCatchTransformer, self).generic_visit(node)
415695
def _handle_for(self, node, scope, ctxt, stream):
        
        self._dlog("handling for")
        if node.init is not None:
            # perform the init
            self._handle_node(node.init, scope, ctxt, stream)

        while node.cond is None or self._handle_node(node.cond, scope, ctxt, stream):
            if node.stmt is not None:
                try:
                    # do the for body
                    self._handle_node(node.stmt, scope, ctxt, stream)
                except errors.InterpBreak as e:
                    break
                
                # we still need to interpret the "next" statement,
                # so just pass
                except errors.InterpContinue as e:
                    pass

            if node.next is not None:
                # do the next statement
                self._handle_node(node.next, scope, ctxt, stream)
1247147
protected void initErrorPage(XmlParser.Node node)
    {
        String error=node.getString("error-code",false,true);
        if(error==null||error.length()==0)
            error=node.getString("exception-type",false,true);
        String location=node.getString("location",false,true);
        getWebApplicationContext().setErrorPage(error,location);
    }
933285
function checkArrowFunc(node) {
            const body = node.body;

            if (isConditional(body) && !(allowParens && astUtils.isParenthesised(sourceCode, body))) {
                context.report({
                    node,
                    messageId: "confusing",
                    fix(fixer) {

                        // if `allowParens` is not set to true dont bother wrapping in parens
                        return allowParens && fixer.replaceText(node.body, `(${sourceCode.getText(node.body)})`);
                    }
                });
            }
        }
71253
Optional<Fix> deleteFix(TryTree tree, ImmutableList<CatchTree> catchBlocks, VisitorState state) {
    SuggestedFix.Builder fix = SuggestedFix.builder();
    if (tree.getFinallyBlock() != null || catchBlocks.size() < tree.getCatches().size()) {
      // If the try statement has a finally region, or other catch blocks, delete only the
      // unnecessary blocks.
      catchBlocks.forEach(fix::delete);
    } else {
      // The try statement has no finally region and all catch blocks are unnecessary. Replace it
      // with the try statements, deleting all catches.
      List<? extends StatementTree> tryStatements = tree.getBlock().getStatements();

      // If the try block is empty, all of the catches are dead, so just delete the whole try and
      // don't modify the signature of the method
      if (tryStatements.isEmpty()) {
        return Optional.of(fix.delete(tree).build());
      } else {
        String source = state.getSourceCode().toString();
        // Replace the full region to work around a GJF partial formatting bug that prevents it from
        // re-indenting unchanged lines. This means that fixes may overlap, but that's (hopefully)
        // unlikely.
        // TODO(b/24140798): emit more precise replacements if GJF is fixed
        fix.replace(
            tree,
            source.substring(
                ((JCTree) tryStatements.get(0)).getStartPosition(),
                state.getEndPosition(Iterables.getLast(tryStatements))));
      }
    }
    MethodTree enclosing = findEnclosing(state.getPath());
    if (enclosing == null) {
      // There isn't an enclosing method, possibly because we're in a lambda or initializer block.
      return Optional.empty();
    }
    if (isExpectedExceptionTest(ASTHelpers.getSymbol(enclosing), state)) {
      // Replacing the original exception with fail() may break badly-structured expected-exception
      // tests, so don't use that fix for methods annotated with @Test(expected=...).
      return Optional.empty();
    }

    // Fix up the enclosing method's throws declaration to include the new thrown exception types.
    Collection<Type> thrownTypes = ASTHelpers.getSymbol(enclosing).getThrownTypes();
    Types types = state.getTypes();
    // Find all types in the deleted catch blocks that are not already in the throws declaration.
    ImmutableList<Type> toThrow =
        catchBlocks.stream()
            .map(c -> ASTHelpers.getType(c.getParameter()))
            // convert multi-catch to a list of component types
            .flatMap(
                t ->
                    t instanceof UnionClassType
                        ? ImmutableList.copyOf(((UnionClassType) t).getAlternativeTypes()).stream()
                        : Stream.of(t))
            .filter(t -> thrownTypes.stream().noneMatch(x -> types.isAssignable(t, x)))
            .collect(toImmutableList());
    if (!toThrow.isEmpty()) {
      if (!JUnitMatchers.TEST_CASE.matches(enclosing, state)) {
        // Don't add throws declarations to methods that don't look like test cases, since it may
        // not be a safe local refactoring.
        return Optional.empty();
      }
      String throwsString =
          toThrow.stream()
              .map(t -> SuggestedFixes.qualifyType(state, fix, t))
              .distinct()
              .collect(joining(", "));
      if (enclosing.getThrows().isEmpty()) {
        // Add a new throws declaration.
        fix.prefixWith(enclosing.getBody(), "throws " + throwsString);
      } else {
        // Append to an existing throws declaration.
        fix.postfixWith(Iterables.getLast(enclosing.getThrows()), ", " + throwsString);
      }
    }
    return Optional.of(fix.build());
  }
380757
def on_assert(self, node):    # ('test', 'msg')
        """"""
        if not self.run(node.test):
            self.raise_exception(node, exc=AssertionError, msg=node.msg)
        return True
605749
def raise_error(self, message, *params, **key_params):
        
        
        s = 'Parser error in '

        self.xml_node_stack.reverse()
        if len(self.xml_node_stack) > 1:
            node = self.xml_node_stack[0]
            s += '<{0}'.format(node.tag)
            if 'name' in node.lattrib:
                s += ' name=\"{0}\"'.format(node.lattrib['name'])
            if 'id' in node.lattrib:
                s += ' id=\"{0}\"'.format(node.lattrib['id'])
            s += '>'

        for node in self.xml_node_stack[1:]:
            s += '.<{0}'.format(node.tag)
            if 'name' in node.lattrib:
                s += ' name=\"{0}\"'.format(node.lattrib['name'])
            if 'id' in node.lattrib:
                s += ' id=\"{0}\"'.format(node.lattrib['id'])
            s += '>'

        s += ':\n  ' + message

        raise ParseError(s, *params, **key_params)

        self.xml_node_stack.reverse()
1029851
function(node, name) {
    this.acceptKey(node, name);

    if (!node[name]) {
      throw new Exception(node.type + ' requires ' + name);
    }
  }
1224303
protected void addError(String message, ASTNode node, SourceUnit source) {
        source.getErrorCollector().addErrorAndContinue(new SyntaxErrorMessage(new SyntaxException(
                message,  node.getLineNumber(), node.getColumnNumber(), node.getLastLineNumber(), node.getLastColumnNumber()
                ), source));
    }
760814
def _add_check(self, node, run, language, is_code_node):
        """"""
        def run_check():
            """Yield errors."""
            all_results = run()
            if all_results is not None:
                if all_results:
                    for result in all_results:
                        error_offset = result[0] - 1

                        line_number = getattr(node, 'line', None)
                        if line_number is not None:
                            yield (
                                beginning_of_code_block(
                                    node=node,
                                    line_number=line_number,
                                    full_contents=self.contents,
                                    is_code_node=is_code_node) +
                                error_offset,
                                '({}) {}'.format(language, result[1]))
                else:
                    yield (self.filename, 0, 'unknown error')
        self.checkers.append(run_check)
61259
def visit_ExceptHandler(self, node):
        """"""
        currs = (node,)
        raises = ()
        for n in node.body:
            self.result.add_node(n)
            for curr in currs:
                self.result.add_edge(curr, n)
            currs, nraises = self.visit(n)
            raises += nraises
        return currs, raises
1052891
def _add_catch(self, catch_block):
        
        assert isinstance(catch_block, self.CodeCatchBlock)
        self.catches.append(catch_block)
1059170
def run(self, node):
        
        if not self.checker_applies(node):
            return

        issues = []
        for body in node.body:
            if not isinstance(body, ast.ClassDef):
                continue
            for element in body.body:
                if not isinstance(element, ast.Assign):
                    continue
                for target in element.targets:
                    if target.id == 'fields' and self.is_string_dunder_all(element):
                        issues.append(
                            DJ07(
                                lineno=node.lineno,
                                col=node.col_offset,
                            )
                        )
                    elif target.id == 'exclude':
                        issues.append(
                            DJ06(
                                lineno=node.lineno,
                                col=node.col_offset,
                            )
                        )
        return issues
892957
private function isIncludeExceptionNode(Node $node): bool
    {
        foreach ($node->children['class']->children as $class) {
            if ($class->children['name'] === 'Exception') {
                return true;
            }
        }

        return false;
    }
147438
function(node) {
			// 1 * foo
			var nonNumericOperand = options.number && isMultiplyByOne(node) && getNonNumericOperand(node);
			if (nonNumericOperand) {
				context.report(
					node,
					ProblemMessages.noImplicitCoercionNumber,
					{
						code: context.getSource(nonNumericOperand)
					});
			}

			// "" + foo
			if (options.string && isConcatWithEmptyString(node)) {
				context.report(
					node,
					ProblemMessages.noImplicitCoercionString,
					{
						code: context.getSource(getOtherOperand(node, ""))
					});
			}
		}
1340959
public static void wrapMethodBodyInTryCatchDebugStatements(MethodNode methodNode) {
        BlockStatement code = (BlockStatement) methodNode.getCode();
        BlockStatement newCode = new BlockStatement();
        TryCatchStatement tryCatchStatement = new TryCatchStatement(code, new BlockStatement());
        newCode.addStatement(tryCatchStatement);
        methodNode.setCode(newCode);
        BlockStatement catchBlock = new BlockStatement();
        ArgumentListExpression logArguments = new ArgumentListExpression();
        logArguments.addExpression(new BinaryExpression(new ConstantExpression("Error initializing class: "),Token.newSymbol(Types.PLUS, 0, 0),new VariableExpression("e")));
        logArguments.addExpression(new VariableExpression("e"));
        catchBlock.addStatement(new ExpressionStatement(new MethodCallExpression(new VariableExpression("log"), "error", logArguments)));
        tryCatchStatement.addCatch(new CatchStatement(new Parameter(new ClassNode(Throwable.class), "e"),catchBlock));
    }
891884
def p_statement_try(p):
    ''
    p[0] = ast.Try(p[3], [ast.Catch(p[7], ast.Variable(p[8], lineno=p.lineno(8)),
                                    p[11], lineno=p.lineno(5))] + p[13],
                   lineno=p.lineno(1))