001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2026 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 *
047 * @since 3.2
048 */
049@StatelessCheck
050public final class IllegalCatchCheck extends AbstractCheck {
051
052    /**
053     * A key is pointing to the warning message text in "messages.properties" file.
054     */
055    public static final String MSG_KEY = "illegal.catch";
056
057    /** Specify exception class names to reject. */
058    private final Set<String> illegalClassNames = Arrays.stream(new String[] {"Exception", "Error",
059        "RuntimeException", "Throwable", "java.lang.Error", "java.lang.Exception",
060        "java.lang.RuntimeException", "java.lang.Throwable", })
061            .collect(Collectors.toCollection(HashSet::new));
062
063    /**
064     * Creates a new {@code IllegalCatchCheck} instance.
065     */
066    public IllegalCatchCheck() {
067        // no code by default
068    }
069
070    /**
071     * Setter to specify exception class names to reject.
072     *
073     * @param classNames
074     *            array of illegal exception classes
075     * @since 3.2
076     */
077    public void setIllegalClassNames(final String... classNames) {
078        illegalClassNames.clear();
079        illegalClassNames.addAll(
080                CheckUtil.parseClassNames(classNames));
081    }
082
083    @Override
084    public int[] getDefaultTokens() {
085        return getRequiredTokens();
086    }
087
088    @Override
089    public int[] getRequiredTokens() {
090        return new int[] {TokenTypes.LITERAL_CATCH};
091    }
092
093    @Override
094    public int[] getAcceptableTokens() {
095        return getRequiredTokens();
096    }
097
098    @Override
099    public void visitToken(DetailAST detailAST) {
100        final DetailAST parameterDef =
101            detailAST.findFirstToken(TokenTypes.PARAMETER_DEF);
102        final DetailAST excTypeParent =
103                parameterDef.findFirstToken(TokenTypes.TYPE);
104
105        DetailAST currentNode = excTypeParent.getFirstChild();
106        while (currentNode != null) {
107            final FullIdent ident = FullIdent.createFullIdent(currentNode);
108            final String identText = ident.getText();
109            if (illegalClassNames.contains(identText)) {
110                log(detailAST, MSG_KEY, identText);
111            }
112            currentNode = currentNode.getNextSibling();
113        }
114    }
115
116}