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