001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2019 the original author or authors.
004//
005// This library is free software; you can redistribute it and/or
006// modify it under the terms of the GNU Lesser General Public
007// License as published by the Free Software Foundation; either
008// version 2.1 of the License, or (at your option) any later version.
009//
010// This library is distributed in the hope that it will be useful,
011// but WITHOUT ANY WARRANTY; without even the implied warranty of
012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013// Lesser General Public License for more details.
014//
015// You should have received a copy of the GNU Lesser General Public
016// License along with this library; if not, write to the Free Software
017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
018////////////////////////////////////////////////////////////////////////////////
019
020package com.puppycrawl.tools.checkstyle.checks.coding;
021
022import java.util.Arrays;
023import java.util.LinkedList;
024import java.util.List;
025import java.util.Set;
026import java.util.stream.Collectors;
027
028import com.puppycrawl.tools.checkstyle.StatelessCheck;
029import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
030import com.puppycrawl.tools.checkstyle.api.DetailAST;
031import com.puppycrawl.tools.checkstyle.api.FullIdent;
032import com.puppycrawl.tools.checkstyle.api.TokenTypes;
033import com.puppycrawl.tools.checkstyle.utils.CheckUtil;
034
035/**
036 * <p>
037 * Checks that certain exception types do not appear in a {@code catch} statement.
038 * </p>
039 * <p>
040 * Rationale: catching {@code java.lang.Exception}, {@code java.lang.Error} or
041 * {@code java.lang.RuntimeException} is almost never acceptable.
042 * Novice developers often simply catch Exception in an attempt to handle
043 * multiple exception classes. This unfortunately leads to code that inadvertently
044 * catches {@code NullPointerException}, {@code OutOfMemoryError}, etc.
045 * </p>
046 * <ul>
047 * <li>
048 * Property {@code illegalClassNames} - Specify exception class names to reject.
049 * Default value is {@code Error, Exception, RuntimeException, Throwable, java.lang.Error,
050 * java.lang.Exception, java.lang.RuntimeException, java.lang.Throwable}.
051 * </li>
052 * </ul>
053 * <p>
054 * To configure the check:
055 * </p>
056 * <pre>
057 * &lt;module name=&quot;IllegalCatch&quot;/&gt;
058 * </pre>
059 *
060 * @since 3.2
061 */
062@StatelessCheck
063public final class IllegalCatchCheck extends AbstractCheck {
064
065    /**
066     * A key is pointing to the warning message text in "messages.properties"
067     * file.
068     */
069    public static final String MSG_KEY = "illegal.catch";
070
071    /** Specify exception class names to reject. */
072    private final Set<String> illegalClassNames = Arrays.stream(new String[] {"Exception", "Error",
073        "RuntimeException", "Throwable", "java.lang.Error", "java.lang.Exception",
074        "java.lang.RuntimeException", "java.lang.Throwable", }).collect(Collectors.toSet());
075
076    /**
077     * Setter to specify exception class names to reject.
078     *
079     * @param classNames
080     *            array of illegal exception classes
081     */
082    public void setIllegalClassNames(final String... classNames) {
083        illegalClassNames.clear();
084        illegalClassNames.addAll(
085                CheckUtil.parseClassNames(classNames));
086    }
087
088    @Override
089    public int[] getDefaultTokens() {
090        return getRequiredTokens();
091    }
092
093    @Override
094    public int[] getRequiredTokens() {
095        return new int[] {TokenTypes.LITERAL_CATCH};
096    }
097
098    @Override
099    public int[] getAcceptableTokens() {
100        return getRequiredTokens();
101    }
102
103    @Override
104    public void visitToken(DetailAST detailAST) {
105        final DetailAST parameterDef =
106            detailAST.findFirstToken(TokenTypes.PARAMETER_DEF);
107        final DetailAST excTypeParent =
108                parameterDef.findFirstToken(TokenTypes.TYPE);
109        final List<DetailAST> excTypes = getAllExceptionTypes(excTypeParent);
110
111        for (DetailAST excType : excTypes) {
112            final FullIdent ident = FullIdent.createFullIdent(excType);
113
114            if (illegalClassNames.contains(ident.getText())) {
115                log(detailAST, MSG_KEY, ident.getText());
116            }
117        }
118    }
119
120    /**
121     * Finds all exception types in current catch.
122     * We need it till we can have few different exception types into one catch.
123     * @param parentToken - parent node for types (TYPE or BOR)
124     * @return list, that contains all exception types in current catch
125     */
126    private static List<DetailAST> getAllExceptionTypes(DetailAST parentToken) {
127        DetailAST currentNode = parentToken.getFirstChild();
128        final List<DetailAST> exceptionTypes = new LinkedList<>();
129        if (currentNode.getType() == TokenTypes.BOR) {
130            exceptionTypes.addAll(getAllExceptionTypes(currentNode));
131            currentNode = currentNode.getNextSibling();
132            exceptionTypes.add(currentNode);
133        }
134        else {
135            do {
136                exceptionTypes.add(currentNode);
137                currentNode = currentNode.getNextSibling();
138            } while (currentNode != null);
139        }
140        return exceptionTypes;
141    }
142
143}