001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2014 Oliver Burn 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//////////////////////////////////////////////////////////////////////////////// 019package com.puppycrawl.tools.checkstyle.checks.coding; 020 021import com.puppycrawl.tools.checkstyle.api.DetailAST; 022import com.puppycrawl.tools.checkstyle.api.TokenTypes; 023 024/** 025 * Restricts nested try-catch-finally blocks to a specified depth (default = 1). 026 * @author <a href="mailto:simon@redhillconsulting.com.au">Simon Harris</a> 027 */ 028public final class NestedTryDepthCheck extends AbstractNestedDepthCheck 029{ 030 /** default allowed nesting depth */ 031 private static final int DEFAULT_MAX = 1; 032 033 /** Creates new check instance with default allowed nesting depth. */ 034 public NestedTryDepthCheck() 035 { 036 super(DEFAULT_MAX); 037 } 038 039 @Override 040 public int[] getDefaultTokens() 041 { 042 return new int[] {TokenTypes.LITERAL_TRY}; 043 } 044 045 @Override 046 public void visitToken(DetailAST ast) 047 { 048 switch (ast.getType()) { 049 case TokenTypes.LITERAL_TRY: 050 visitLiteralTry(ast); 051 break; 052 default: 053 throw new IllegalStateException(ast.toString()); 054 } 055 } 056 057 @Override 058 public void leaveToken(DetailAST ast) 059 { 060 switch (ast.getType()) { 061 case TokenTypes.LITERAL_TRY: 062 leaveLiteralTry(); 063 break; 064 default: 065 throw new IllegalStateException(ast.toString()); 066 } 067 } 068 069 /** 070 * Increases current nesting depth. 071 * @param literalTry node for try. 072 */ 073 private void visitLiteralTry(DetailAST literalTry) 074 { 075 nestIn(literalTry, "nested.try.depth"); 076 } 077 078 /** Decreases current nesting depth */ 079 private void leaveLiteralTry() 080 { 081 nestOut(); 082 } 083}