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"
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     * Creates a new {@code IllegalCatchCheck} instance.
066     */
067    public IllegalCatchCheck() {
068        // no code by default
069    }
070
071    /**
072     * Setter to specify exception class names to reject.
073     *
074     * @param classNames
075     *            array of illegal exception classes
076     * @since 3.2
077     */
078    public void setIllegalClassNames(final String... classNames) {
079        illegalClassNames.clear();
080        illegalClassNames.addAll(
081                CheckUtil.parseClassNames(classNames));
082    }
083
084    @Override
085    public int[] getDefaultTokens() {
086        return getRequiredTokens();
087    }
088
089    @Override
090    public int[] getRequiredTokens() {
091        return new int[] {TokenTypes.LITERAL_CATCH};
092    }
093
094    @Override
095    public int[] getAcceptableTokens() {
096        return getRequiredTokens();
097    }
098
099    @Override
100    public void visitToken(DetailAST detailAST) {
101        final DetailAST parameterDef =
102            detailAST.findFirstToken(TokenTypes.PARAMETER_DEF);
103        final DetailAST excTypeParent =
104                parameterDef.findFirstToken(TokenTypes.TYPE);
105
106        DetailAST currentNode = excTypeParent.getFirstChild();
107        while (currentNode != null) {
108            final FullIdent ident = FullIdent.createFullIdent(currentNode);
109            final String identText = ident.getText();
110            if (illegalClassNames.contains(identText)) {
111                log(detailAST, MSG_KEY, identText);
112            }
113            currentNode = currentNode.getNextSibling();
114        }
115    }
116
117}