001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2019 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.design; 021 022import com.puppycrawl.tools.checkstyle.StatelessCheck; 023import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 024import com.puppycrawl.tools.checkstyle.api.DetailAST; 025import com.puppycrawl.tools.checkstyle.api.TokenTypes; 026 027/** 028 * <p> 029 * Restricts throws statements to a specified count (4 by default). 030 * Methods with "Override" or "java.lang.Override" annotation are skipped 031 * from validation as current class cannot change signature of these methods. 032 * </p> 033 * <p> 034 * Rationale: 035 * Exceptions form part of a method's interface. Declaring 036 * a method to throw too many differently rooted 037 * exceptions makes exception handling onerous and leads 038 * to poor programming practices such as writing code like 039 * {@code catch(Exception ex)}. 4 is the empirical value which is based 040 * on reports that we had for the ThrowsCountCheck over big projects 041 * such as OpenJDK. This check also forces developers to put exceptions 042 * into a hierarchy such that in the simplest 043 * case, only one type of exception need be checked for by 044 * a caller but any subclasses can be caught 045 * specifically if necessary. For more information on rules 046 * for the exceptions and their issues, see Effective Java: 047 * Programming Language Guide Second Edition 048 * by Joshua Bloch pages 264-273. 049 * </p> 050 * <p> 051 * <b>ignorePrivateMethods</b> - allows to skip private methods as they do 052 * not cause problems for other classes. 053 * </p> 054 * <ul> 055 * <li> 056 * Property {@code max} - Specify maximum allowed number of throws statements. 057 * Default value is {@code 4}. 058 * </li> 059 * <li> 060 * Property {@code ignorePrivateMethods} - Allow private methods to be ignored. 061 * Default value is {@code true}. 062 * </li> 063 * </ul> 064 * <p> 065 * To configure the check so that it doesn't allow more than two throws per method: 066 * </p> 067 * <pre> 068 * <module name="ThrowsCount"> 069 * <property name="max" value="2"/> 070 * </module> 071 * </pre> 072 * <p> 073 * To configure the check so that it doesn't skip private methods: 074 * </p> 075 * <pre> 076 * <module name="ThrowsCount"> 077 * <property name="ignorePrivateMethods" value="false"/> 078 * </module> 079 * </pre> 080 * 081 * @since 3.2 082 */ 083@StatelessCheck 084public final class ThrowsCountCheck extends AbstractCheck { 085 086 /** 087 * A key is pointing to the warning message text in "messages.properties" 088 * file. 089 */ 090 public static final String MSG_KEY = "throws.count"; 091 092 /** Default value of max property. */ 093 private static final int DEFAULT_MAX = 4; 094 095 /** Allow private methods to be ignored. */ 096 private boolean ignorePrivateMethods = true; 097 098 /** Specify maximum allowed number of throws statements. */ 099 private int max; 100 101 /** Creates new instance of the check. */ 102 public ThrowsCountCheck() { 103 max = DEFAULT_MAX; 104 } 105 106 @Override 107 public int[] getDefaultTokens() { 108 return getRequiredTokens(); 109 } 110 111 @Override 112 public int[] getRequiredTokens() { 113 return new int[] { 114 TokenTypes.LITERAL_THROWS, 115 }; 116 } 117 118 @Override 119 public int[] getAcceptableTokens() { 120 return getRequiredTokens(); 121 } 122 123 /** 124 * Setter to allow private methods to be ignored. 125 * @param ignorePrivateMethods whether private methods must be ignored. 126 */ 127 public void setIgnorePrivateMethods(boolean ignorePrivateMethods) { 128 this.ignorePrivateMethods = ignorePrivateMethods; 129 } 130 131 /** 132 * Setter to specify maximum allowed number of throws statements. 133 * @param max maximum allowed throws statements. 134 */ 135 public void setMax(int max) { 136 this.max = max; 137 } 138 139 @Override 140 public void visitToken(DetailAST ast) { 141 if (ast.getType() == TokenTypes.LITERAL_THROWS) { 142 visitLiteralThrows(ast); 143 } 144 else { 145 throw new IllegalStateException(ast.toString()); 146 } 147 } 148 149 /** 150 * Checks number of throws statements. 151 * @param ast throws for check. 152 */ 153 private void visitLiteralThrows(DetailAST ast) { 154 if ((!ignorePrivateMethods || !isInPrivateMethod(ast)) 155 && !isOverriding(ast)) { 156 // Account for all the commas! 157 final int count = (ast.getChildCount() + 1) / 2; 158 if (count > max) { 159 log(ast, MSG_KEY, count, max); 160 } 161 } 162 } 163 164 /** 165 * Check if a method has annotation @Override. 166 * @param ast throws, which is being checked. 167 * @return true, if a method has annotation @Override. 168 */ 169 private static boolean isOverriding(DetailAST ast) { 170 final DetailAST modifiers = ast.getParent().findFirstToken(TokenTypes.MODIFIERS); 171 boolean isOverriding = false; 172 DetailAST child = modifiers.getFirstChild(); 173 while (child != null) { 174 if (child.getType() == TokenTypes.ANNOTATION 175 && "Override".equals(getAnnotationName(child))) { 176 isOverriding = true; 177 break; 178 } 179 child = child.getNextSibling(); 180 } 181 return isOverriding; 182 } 183 184 /** 185 * Gets name of an annotation. 186 * @param annotation to get name of. 187 * @return name of an annotation. 188 */ 189 private static String getAnnotationName(DetailAST annotation) { 190 final DetailAST dotAst = annotation.findFirstToken(TokenTypes.DOT); 191 final String name; 192 if (dotAst == null) { 193 name = annotation.findFirstToken(TokenTypes.IDENT).getText(); 194 } 195 else { 196 name = dotAst.findFirstToken(TokenTypes.IDENT).getText(); 197 } 198 return name; 199 } 200 201 /** 202 * Checks if method, which throws an exception is private. 203 * @param ast throws, which is being checked. 204 * @return true, if method, which throws an exception is private. 205 */ 206 private static boolean isInPrivateMethod(DetailAST ast) { 207 final DetailAST methodModifiers = ast.getParent().findFirstToken(TokenTypes.MODIFIERS); 208 return methodModifiers.findFirstToken(TokenTypes.LITERAL_PRIVATE) != null; 209 } 210 211}