001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2020 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.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.AnnotationUtil;
033import com.puppycrawl.tools.checkstyle.utils.CheckUtil;
034
035/**
036 * <p>
037 * Checks that specified types are not declared to be thrown.
038 * Declaring that a method throws {@code java.lang.Error} or
039 * {@code java.lang.RuntimeException} is almost never acceptable.
040 * </p>
041 * <ul>
042 * <li>
043 * Property {@code illegalClassNames} - Specify throw class names to reject.
044 * Type is {@code java.lang.String[]}.
045 * Default value is {@code Error, RuntimeException, Throwable, java.lang.Error,
046 * java.lang.RuntimeException, java.lang.Throwable}.
047 * </li>
048 * <li>
049 * Property {@code ignoredMethodNames} - Specify names of methods to ignore.
050 * Type is {@code java.lang.String[]}.
051 * Default value is {@code finalize}.
052 * </li>
053 * <li>
054 * Property {@code ignoreOverriddenMethods} - allow to ignore checking overridden methods
055 * (marked with {@code Override} or {@code java.lang.Override} annotation).
056 * Type is {@code boolean}.
057 * Default value is {@code true}.
058 * </li>
059 * </ul>
060 * <p>
061 * To configure the check:
062 * </p>
063 * <pre>
064 * &lt;module name="IllegalThrows"/&gt;
065 * </pre>
066 * <p>Example:</p>
067 * <pre>
068 * public class Test {
069 *   public void func1() throws RuntimeException {} // violation
070 *   public void func2() throws Exception {}  // ok
071 *   public void func3() throws Error {}  // violation
072 *   public void func4() throws Throwable {} // violation
073 *   public void func5() throws NullPointerException {} // ok
074 *   &#064;Override
075 *   public void toString() throws Error {} // ok
076 * }
077 * </pre>
078 * <p>
079 * To configure the check rejecting throws NullPointerException from methods:
080 * </p>
081 * <pre>
082 * &lt;module name="IllegalThrows"&gt;
083 *   &lt;property name="illegalClassNames" value="NullPointerException"/&gt;
084 * &lt;/module&gt;
085 * </pre>
086 * <p>Example:</p>
087 * <pre>
088 * public class Test {
089 *   public void func1() throws RuntimeException {} // ok
090 *   public void func2() throws Exception {}  // ok
091 *   public void func3() throws Error {}  // ok
092 *   public void func4() throws Throwable {} // ok
093 *   public void func5() throws NullPointerException {} // violation
094 *   &#064;Override
095 *   public void toString() throws Error {} // ok
096 * }
097 * </pre>
098 * <p>
099 * To configure the check ignoring method named "func1()":
100 * </p>
101 * <pre>
102 * &lt;module name="IllegalThrows"&gt;
103 *   &lt;property name="ignoredMethodNames" value="func1"/&gt;
104 * &lt;/module&gt;
105 * </pre>
106 * <p>Example:</p>
107 * <pre>
108 * public class Test {
109 *   public void func1() throws RuntimeException {} // ok
110 *   public void func2() throws Exception {}  // ok
111 *   public void func3() throws Error {}  // violation
112 *   public void func4() throws Throwable {} // violation
113 *   public void func5() throws NullPointerException {} // ok
114 *   &#064;Override
115 *   public void toString() throws Error {} // ok
116 * }
117 * </pre>
118 * <p>
119 * To configure the check to warn on overridden methods:
120 * </p>
121 * <pre>
122 * &lt;module name=&quot;IllegalThrows&quot;&gt;
123 *   &lt;property name=&quot;ignoreOverriddenMethods&quot; value=&quot;false&quot;/&gt;
124 * &lt;/module&gt;
125 * </pre>
126 * <p>Example:</p>
127 * <pre>
128 * public class Test {
129 *   public void func1() throws RuntimeException {} // violation
130 *   public void func2() throws Exception {}  // ok
131 *   public void func3() throws Error {}  // violation
132 *   public void func4() throws Throwable {} // violation
133 *   public void func5() throws NullPointerException {} // ok
134 *   &#064;Override
135 *   public void toString() throws Error {} // violation
136 * }
137 * </pre>
138 * <p>
139 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker}
140 * </p>
141 * <p>
142 * Violation Message Keys:
143 * </p>
144 * <ul>
145 * <li>
146 * {@code illegal.throw}
147 * </li>
148 * </ul>
149 *
150 * @since 4.0
151 */
152@StatelessCheck
153public final class IllegalThrowsCheck extends AbstractCheck {
154
155    /**
156     * A key is pointing to the warning message text in "messages.properties"
157     * file.
158     */
159    public static final String MSG_KEY = "illegal.throw";
160
161    /** Specify names of methods to ignore. */
162    private final Set<String> ignoredMethodNames =
163        Arrays.stream(new String[] {"finalize", }).collect(Collectors.toSet());
164
165    /** Specify throw class names to reject. */
166    private final Set<String> illegalClassNames = Arrays.stream(
167        new String[] {"Error", "RuntimeException", "Throwable", "java.lang.Error",
168                      "java.lang.RuntimeException", "java.lang.Throwable", })
169        .collect(Collectors.toSet());
170
171    /**
172     * Allow to ignore checking overridden methods (marked with {@code Override}
173     * or {@code java.lang.Override} annotation).
174     */
175    private boolean ignoreOverriddenMethods = true;
176
177    /**
178     * Setter to specify throw class names to reject.
179     *
180     * @param classNames
181     *            array of illegal exception classes
182     */
183    public void setIllegalClassNames(final String... classNames) {
184        illegalClassNames.clear();
185        illegalClassNames.addAll(
186                CheckUtil.parseClassNames(classNames));
187    }
188
189    @Override
190    public int[] getDefaultTokens() {
191        return getRequiredTokens();
192    }
193
194    @Override
195    public int[] getRequiredTokens() {
196        return new int[] {TokenTypes.LITERAL_THROWS};
197    }
198
199    @Override
200    public int[] getAcceptableTokens() {
201        return getRequiredTokens();
202    }
203
204    @Override
205    public void visitToken(DetailAST detailAST) {
206        final DetailAST methodDef = detailAST.getParent();
207        // Check if the method with the given name should be ignored.
208        if (!isIgnorableMethod(methodDef)) {
209            DetailAST token = detailAST.getFirstChild();
210            while (token != null) {
211                final FullIdent ident = FullIdent.createFullIdent(token);
212                if (illegalClassNames.contains(ident.getText())) {
213                    log(token, MSG_KEY, ident.getText());
214                }
215                token = token.getNextSibling();
216            }
217        }
218    }
219
220    /**
221     * Checks if current method is ignorable due to Check's properties.
222     *
223     * @param methodDef {@link TokenTypes#METHOD_DEF METHOD_DEF}
224     * @return true if method is ignorable.
225     */
226    private boolean isIgnorableMethod(DetailAST methodDef) {
227        return shouldIgnoreMethod(methodDef.findFirstToken(TokenTypes.IDENT).getText())
228            || ignoreOverriddenMethods
229               && (AnnotationUtil.containsAnnotation(methodDef, "Override")
230                  || AnnotationUtil.containsAnnotation(methodDef, "java.lang.Override"));
231    }
232
233    /**
234     * Check if the method is specified in the ignore method list.
235     *
236     * @param name the name to check
237     * @return whether the method with the passed name should be ignored
238     */
239    private boolean shouldIgnoreMethod(String name) {
240        return ignoredMethodNames.contains(name);
241    }
242
243    /**
244     * Setter to specify names of methods to ignore.
245     *
246     * @param methodNames array of ignored method names
247     */
248    public void setIgnoredMethodNames(String... methodNames) {
249        ignoredMethodNames.clear();
250        Collections.addAll(ignoredMethodNames, methodNames);
251    }
252
253    /**
254     * Setter to allow to ignore checking overridden methods
255     * (marked with {@code Override} or {@code java.lang.Override} annotation).
256     *
257     * @param ignoreOverriddenMethods Check's property.
258     */
259    public void setIgnoreOverriddenMethods(boolean ignoreOverriddenMethods) {
260        this.ignoreOverriddenMethods = ignoreOverriddenMethods;
261    }
262
263}