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.Collections;
024import java.util.HashSet;
025import java.util.Set;
026import java.util.stream.Collectors;
027
028import com.puppycrawl.tools.checkstyle.StatelessCheck;
029import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
030import com.puppycrawl.tools.checkstyle.api.DetailAST;
031import com.puppycrawl.tools.checkstyle.api.FullIdent;
032import com.puppycrawl.tools.checkstyle.api.TokenTypes;
033import com.puppycrawl.tools.checkstyle.utils.AnnotationUtil;
034import com.puppycrawl.tools.checkstyle.utils.CheckUtil;
035
036/**
037 * <div>
038 * Checks that specified types are not declared to be thrown.
039 * Declaring that a method throws {@code java.lang.Error} or
040 * {@code java.lang.RuntimeException} is almost never acceptable.
041 * </div>
042 *
043 * @since 4.0
044 */
045@StatelessCheck
046public final class IllegalThrowsCheck extends AbstractCheck {
047
048    /**
049     * A key is pointing to the warning message text in "messages.properties"
050     * file.
051     */
052    public static final String MSG_KEY = "illegal.throw";
053
054    /** Specify names of methods to ignore. */
055    private final Set<String> ignoredMethodNames =
056        Arrays.stream(new String[] {"finalize", }).collect(Collectors.toCollection(HashSet::new));
057
058    /** Specify throw class names to reject. */
059    private final Set<String> illegalClassNames = Arrays.stream(
060        new String[] {"Error", "RuntimeException", "Throwable", "java.lang.Error",
061                      "java.lang.RuntimeException", "java.lang.Throwable", })
062        .collect(Collectors.toCollection(HashSet::new));
063
064    /**
065     * Allow to ignore checking overridden methods (marked with {@code Override}
066     * or {@code java.lang.Override} annotation).
067     */
068    private boolean ignoreOverriddenMethods = true;
069
070    /**
071     * Setter to specify throw class names to reject.
072     *
073     * @param classNames
074     *            array of illegal exception classes
075     * @since 4.0
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_THROWS};
091    }
092
093    @Override
094    public int[] getAcceptableTokens() {
095        return getRequiredTokens();
096    }
097
098    @Override
099    public void visitToken(DetailAST detailAST) {
100        final DetailAST methodDef = detailAST.getParent();
101        // Check if the method with the given name should be ignored.
102        if (!isIgnorableMethod(methodDef)) {
103            DetailAST token = detailAST.getFirstChild();
104            while (token != null) {
105                final FullIdent ident = FullIdent.createFullIdent(token);
106                final String identText = ident.getText();
107                if (illegalClassNames.contains(identText)) {
108                    log(token, MSG_KEY, identText);
109                }
110                token = token.getNextSibling();
111            }
112        }
113    }
114
115    /**
116     * Checks if current method is ignorable due to Check's properties.
117     *
118     * @param methodDef {@link TokenTypes#METHOD_DEF METHOD_DEF}
119     * @return true if method is ignorable.
120     */
121    private boolean isIgnorableMethod(DetailAST methodDef) {
122        return shouldIgnoreMethod(methodDef.findFirstToken(TokenTypes.IDENT).getText())
123            || ignoreOverriddenMethods
124               && AnnotationUtil.hasOverrideAnnotation(methodDef);
125    }
126
127    /**
128     * Check if the method is specified in the ignore method list.
129     *
130     * @param name the name to check
131     * @return whether the method with the passed name should be ignored
132     */
133    private boolean shouldIgnoreMethod(String name) {
134        return ignoredMethodNames.contains(name);
135    }
136
137    /**
138     * Setter to specify names of methods to ignore.
139     *
140     * @param methodNames array of ignored method names
141     * @since 5.4
142     */
143    public void setIgnoredMethodNames(String... methodNames) {
144        ignoredMethodNames.clear();
145        Collections.addAll(ignoredMethodNames, methodNames);
146    }
147
148    /**
149     * Setter to allow to ignore checking overridden methods
150     * (marked with {@code Override} or {@code java.lang.Override} annotation).
151     *
152     * @param ignoreOverriddenMethods Check's property.
153     * @since 6.4
154     */
155    public void setIgnoreOverriddenMethods(boolean ignoreOverriddenMethods) {
156        this.ignoreOverriddenMethods = ignoreOverriddenMethods;
157    }
158
159}