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.LinkedList; 024import java.util.List; 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.CheckUtil; 034 035/** 036 * <p> 037 * Checks that certain exception types do not appear in a {@code catch} statement. 038 * </p> 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 * <ul> 047 * <li> 048 * Property {@code illegalClassNames} - Specify exception class names to reject. 049 * Default value is {@code Error, Exception, RuntimeException, Throwable, java.lang.Error, 050 * java.lang.Exception, java.lang.RuntimeException, java.lang.Throwable}. 051 * </li> 052 * </ul> 053 * <p> 054 * To configure the check: 055 * </p> 056 * <pre> 057 * <module name="IllegalCatch"/> 058 * </pre> 059 * <p>Example:</p> 060 * <pre> 061 * try { 062 * // some code here 063 * } catch (Exception e) { // violation 064 * 065 * } 066 * 067 * try { 068 * // some code here 069 * } catch (ArithmeticException e) { // OK 070 * 071 * } catch (Exception e) { // violation, catching Exception is illegal 072 * and order of catch blocks doesn't matter 073 * } 074 * 075 * try { 076 * // some code here 077 * } catch (ArithmeticException | Exception e) { // violation, catching Exception is illegal 078 * 079 * } 080 * 081 * try { 082 * // some code here 083 * } catch (ArithmeticException e) { // OK 084 * 085 * } 086 * 087 * </pre> 088 * <p> 089 * To configure the check to override the default list 090 * with ArithmeticException and OutOfMemoryError: 091 * </p> 092 * <pre> 093 * <module name="IllegalCatch"> 094 * <property name="illegalClassNames" value="ArithmeticException, 095 * OutOfMemoryError"/> 096 * </module> 097 * </pre> 098 * <p>Example:</p> 099 * <pre> 100 * try { 101 * // some code here 102 * } catch (OutOfMemoryError e) { // violation 103 * 104 * } 105 * 106 * try { 107 * // some code here 108 * } catch (ArithmeticException e) { // violation 109 * 110 * } 111 * 112 * try { 113 * // some code here 114 * } catch (NullPointerException e) { // OK 115 * 116 * } catch (OutOfMemoryError e) { // violation 117 * 118 * } 119 * 120 * try { 121 * // some code here 122 * } catch (ArithmeticException | Exception e) { // violation 123 * 124 * } 125 * 126 * try { 127 * // some code here 128 * } catch (Exception e) { // OK 129 * 130 * } 131 * </pre> 132 * 133 * @since 3.2 134 */ 135@StatelessCheck 136public final class IllegalCatchCheck extends AbstractCheck { 137 138 /** 139 * A key is pointing to the warning message text in "messages.properties" 140 * file. 141 */ 142 public static final String MSG_KEY = "illegal.catch"; 143 144 /** Specify exception class names to reject. */ 145 private final Set<String> illegalClassNames = Arrays.stream(new String[] {"Exception", "Error", 146 "RuntimeException", "Throwable", "java.lang.Error", "java.lang.Exception", 147 "java.lang.RuntimeException", "java.lang.Throwable", }).collect(Collectors.toSet()); 148 149 /** 150 * Setter to specify exception class names to reject. 151 * 152 * @param classNames 153 * array of illegal exception classes 154 */ 155 public void setIllegalClassNames(final String... classNames) { 156 illegalClassNames.clear(); 157 illegalClassNames.addAll( 158 CheckUtil.parseClassNames(classNames)); 159 } 160 161 @Override 162 public int[] getDefaultTokens() { 163 return getRequiredTokens(); 164 } 165 166 @Override 167 public int[] getRequiredTokens() { 168 return new int[] {TokenTypes.LITERAL_CATCH}; 169 } 170 171 @Override 172 public int[] getAcceptableTokens() { 173 return getRequiredTokens(); 174 } 175 176 @Override 177 public void visitToken(DetailAST detailAST) { 178 final DetailAST parameterDef = 179 detailAST.findFirstToken(TokenTypes.PARAMETER_DEF); 180 final DetailAST excTypeParent = 181 parameterDef.findFirstToken(TokenTypes.TYPE); 182 final List<DetailAST> excTypes = getAllExceptionTypes(excTypeParent); 183 184 for (DetailAST excType : excTypes) { 185 final FullIdent ident = FullIdent.createFullIdent(excType); 186 187 if (illegalClassNames.contains(ident.getText())) { 188 log(detailAST, MSG_KEY, ident.getText()); 189 } 190 } 191 } 192 193 /** 194 * Finds all exception types in current catch. 195 * We need it till we can have few different exception types into one catch. 196 * 197 * @param parentToken - parent node for types (TYPE or BOR) 198 * @return list, that contains all exception types in current catch 199 */ 200 private static List<DetailAST> getAllExceptionTypes(DetailAST parentToken) { 201 DetailAST currentNode = parentToken.getFirstChild(); 202 final List<DetailAST> exceptionTypes = new LinkedList<>(); 203 if (currentNode.getType() == TokenTypes.BOR) { 204 exceptionTypes.addAll(getAllExceptionTypes(currentNode)); 205 currentNode = currentNode.getNextSibling(); 206 exceptionTypes.add(currentNode); 207 } 208 else { 209 do { 210 exceptionTypes.add(currentNode); 211 currentNode = currentNode.getNextSibling(); 212 } while (currentNode != null); 213 } 214 return exceptionTypes; 215 } 216 217}