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 * <p>
036 * Checks that certain exception types do not appear in a {@code catch} statement.
037 * </p>
038 * <p>
039 * Rationale: catching {@code java.lang.Exception}, {@code java.lang.Error} or
040 * {@code java.lang.RuntimeException} is almost never acceptable.
041 * Novice developers often simply catch Exception in an attempt to handle
042 * multiple exception classes. This unfortunately leads to code that inadvertently
043 * catches {@code NullPointerException}, {@code OutOfMemoryError}, etc.
044 * </p>
045 * <ul>
046 * <li>
047 * Property {@code illegalClassNames} - Specify exception class names to reject.
048 * Type is {@code java.lang.String[]}.
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 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
055 * </p>
056 * <p>
057 * Violation Message Keys:
058 * </p>
059 * <ul>
060 * <li>
061 * {@code illegal.catch}
062 * </li>
063 * </ul>
064 *
065 * @since 3.2
066 */
067@StatelessCheck
068public final class IllegalCatchCheck extends AbstractCheck {
069
070    /**
071     * A key is pointing to the warning message text in "messages.properties"
072     * file.
073     */
074    public static final String MSG_KEY = "illegal.catch";
075
076    /** Specify exception class names to reject. */
077    private final Set<String> illegalClassNames = Arrays.stream(new String[] {"Exception", "Error",
078        "RuntimeException", "Throwable", "java.lang.Error", "java.lang.Exception",
079        "java.lang.RuntimeException", "java.lang.Throwable", })
080            .collect(Collectors.toCollection(HashSet::new));
081
082    /**
083     * Setter to specify exception class names to reject.
084     *
085     * @param classNames
086     *            array of illegal exception classes
087     * @since 3.2
088     */
089    public void setIllegalClassNames(final String... classNames) {
090        illegalClassNames.clear();
091        illegalClassNames.addAll(
092                CheckUtil.parseClassNames(classNames));
093    }
094
095    @Override
096    public int[] getDefaultTokens() {
097        return getRequiredTokens();
098    }
099
100    @Override
101    public int[] getRequiredTokens() {
102        return new int[] {TokenTypes.LITERAL_CATCH};
103    }
104
105    @Override
106    public int[] getAcceptableTokens() {
107        return getRequiredTokens();
108    }
109
110    @Override
111    public void visitToken(DetailAST detailAST) {
112        final DetailAST parameterDef =
113            detailAST.findFirstToken(TokenTypes.PARAMETER_DEF);
114        final DetailAST excTypeParent =
115                parameterDef.findFirstToken(TokenTypes.TYPE);
116
117        DetailAST currentNode = excTypeParent.getFirstChild();
118        while (currentNode != null) {
119            final FullIdent ident = FullIdent.createFullIdent(currentNode);
120            final String identText = ident.getText();
121            if (illegalClassNames.contains(identText)) {
122                log(detailAST, MSG_KEY, identText);
123            }
124            currentNode = currentNode.getNextSibling();
125        }
126    }
127}