Add rule to make Try Catch a must for all the methods or events or logical code blocks

Jul 24, 2012 at 1:14 PM

Use try . . catch blocks to catch unhandled exceptions.

I want to add a custom rule to validate that Try catch blocks are added to every method or event or a logical code block.

I have written follwing code to check for methods, unfortunatley its not working

Param.RequireNotNull(document, "document");

 

 

 CsDocument document2 = (CsDocument)document;

 

 

if ((document2.RootElement != null) && !document2.RootElement.Generated)

{

 

 

document2.WalkDocument(new CodeWalkerElementVisitor<object>(VisitElement), null, null);

 } 

 

 

private bool VisitElement(CsElement element, CsElement parentElement, object context)

{

 if (element.ElementType == ElementType.Method && !element.Generated)

 {

 var method = (Method)element;

 int totalCountOfCodeLines = GetNumberOfCodeLinesInMethod(method);

 bool isErrorHandled = false;

 foreach (var token in method.Tokens)

{

 var tokenType = token.Text.ToLower();

 if (isErrorHandled == false)

{

 Console.WriteLine("CsTokenType.Try.ToString().ToLower() : " + CsTokenType.Try.ToString().ToLower());

 Console.WriteLine(tokenType);

 

 if (tokenType == CsTokenType.Try.ToString().ToLower())

 {

 

isErrorHandled =true

 

 

return true;

}

}

 

if (isErrorHandled == false)

{

 

base.AddViolation(

element,

 

"TryCatchBlockIsNecessaryForAllCodeBlocks",

 

new object[0]);

 

return true;

}

}

}

 

return true;

}