View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2026 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ///////////////////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.checks.coding;
21  
22  import java.util.Arrays;
23  import java.util.HashSet;
24  import java.util.Set;
25  import java.util.stream.Collectors;
26  
27  import com.puppycrawl.tools.checkstyle.StatelessCheck;
28  import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
29  import com.puppycrawl.tools.checkstyle.api.DetailAST;
30  import com.puppycrawl.tools.checkstyle.api.FullIdent;
31  import com.puppycrawl.tools.checkstyle.api.TokenTypes;
32  import com.puppycrawl.tools.checkstyle.utils.CheckUtil;
33  
34  /**
35   * <div>
36   * Checks that certain exception types do not appear in a {@code catch} statement.
37   * </div>
38   *
39   * <p>
40   * Rationale: catching {@code java.lang.Exception}, {@code java.lang.Error} or
41   * {@code java.lang.RuntimeException} is almost never acceptable.
42   * Novice developers often simply catch Exception in an attempt to handle
43   * multiple exception classes. This unfortunately leads to code that inadvertently
44   * catches {@code NullPointerException}, {@code OutOfMemoryError}, etc.
45   * </p>
46   *
47   * @since 3.2
48   */
49  @StatelessCheck
50  public final class IllegalCatchCheck extends AbstractCheck {
51  
52      /**
53       * A key is pointing to the warning message text in "messages.properties"
54       * file.
55       */
56      public static final String MSG_KEY = "illegal.catch";
57  
58      /** Specify exception class names to reject. */
59      private final Set<String> illegalClassNames = Arrays.stream(new String[] {"Exception", "Error",
60          "RuntimeException", "Throwable", "java.lang.Error", "java.lang.Exception",
61          "java.lang.RuntimeException", "java.lang.Throwable", })
62              .collect(Collectors.toCollection(HashSet::new));
63  
64      /**
65       * Creates a new {@code IllegalCatchCheck} instance.
66       */
67      public IllegalCatchCheck() {
68          // no code by default
69      }
70  
71      /**
72       * Setter to specify exception class names to reject.
73       *
74       * @param classNames
75       *            array of illegal exception classes
76       * @since 3.2
77       */
78      public void setIllegalClassNames(final String... classNames) {
79          illegalClassNames.clear();
80          illegalClassNames.addAll(
81                  CheckUtil.parseClassNames(classNames));
82      }
83  
84      @Override
85      public int[] getDefaultTokens() {
86          return getRequiredTokens();
87      }
88  
89      @Override
90      public int[] getRequiredTokens() {
91          return new int[] {TokenTypes.LITERAL_CATCH};
92      }
93  
94      @Override
95      public int[] getAcceptableTokens() {
96          return getRequiredTokens();
97      }
98  
99      @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 }