001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2024 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.HashSet;
024import java.util.Set;
025import java.util.stream.Collectors;
026
027import com.puppycrawl.tools.checkstyle.StatelessCheck;
028import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
029import com.puppycrawl.tools.checkstyle.api.DetailAST;
030import com.puppycrawl.tools.checkstyle.api.FullIdent;
031import com.puppycrawl.tools.checkstyle.api.TokenTypes;
032import com.puppycrawl.tools.checkstyle.utils.CheckUtil;
033
034/**
035 * <div>
036 * Checks that certain exception types do not appear in a {@code catch} statement.
037 * </div>
038 *
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 * Type is {@code java.lang.String[]}.
050 * Default value is {@code Error, Exception, RuntimeException, Throwable, java.lang.Error,
051 * java.lang.Exception, java.lang.RuntimeException, java.lang.Throwable}.
052 * </li>
053 * </ul>
054 *
055 * <p>
056 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
057 * </p>
058 *
059 * <p>
060 * Violation Message Keys:
061 * </p>
062 * <ul>
063 * <li>
064 * {@code illegal.catch}
065 * </li>
066 * </ul>
067 *
068 * @since 3.2
069 */
070@StatelessCheck
071public final class IllegalCatchCheck extends AbstractCheck {
072
073    /**
074     * A key is pointing to the warning message text in "messages.properties"
075     * file.
076     */
077    public static final String MSG_KEY = "illegal.catch";
078
079    /** Specify exception class names to reject. */
080    private final Set<String> illegalClassNames = Arrays.stream(new String[] {"Exception", "Error",
081        "RuntimeException", "Throwable", "java.lang.Error", "java.lang.Exception",
082        "java.lang.RuntimeException", "java.lang.Throwable", })
083            .collect(Collectors.toCollection(HashSet::new));
084
085    /**
086     * Setter to specify exception class names to reject.
087     *
088     * @param classNames
089     *            array of illegal exception classes
090     * @since 3.2
091     */
092    public void setIllegalClassNames(final String... classNames) {
093        illegalClassNames.clear();
094        illegalClassNames.addAll(
095                CheckUtil.parseClassNames(classNames));
096    }
097
098    @Override
099    public int[] getDefaultTokens() {
100        return getRequiredTokens();
101    }
102
103    @Override
104    public int[] getRequiredTokens() {
105        return new int[] {TokenTypes.LITERAL_CATCH};
106    }
107
108    @Override
109    public int[] getAcceptableTokens() {
110        return getRequiredTokens();
111    }
112
113    @Override
114    public void visitToken(DetailAST detailAST) {
115        final DetailAST parameterDef =
116            detailAST.findFirstToken(TokenTypes.PARAMETER_DEF);
117        final DetailAST excTypeParent =
118                parameterDef.findFirstToken(TokenTypes.TYPE);
119
120        DetailAST currentNode = excTypeParent.getFirstChild();
121        while (currentNode != null) {
122            final FullIdent ident = FullIdent.createFullIdent(currentNode);
123            final String identText = ident.getText();
124            if (illegalClassNames.contains(identText)) {
125                log(detailAST, MSG_KEY, identText);
126            }
127            currentNode = currentNode.getNextSibling();
128        }
129    }
130}