locked
Custom FxCop rule for detecting empty catch blocks?

    Question

  • Hi,

    I'm looking for a custom rule that checks if there are empty catch blocks in a method. If you know of something like this that already exists, that would be great. If you have pointers on how to implement such a rule, that would be great too.

     

    Thanx,

    -KC

    Monday, December 26, 2005 7:45 AM

Answers

  • The easiest way to write a check would look like this:

    1) foreach over all Method.Instructions

    2) On encountering an instruction where Instruction.OpCode == OpCode._Catch, do a forward seek until you encounter an OpCode._EndHandler instruction for which the Instruction.Value matches the opening _Catch instruction. If you encounter a throw instruction, stop seeking and continue processing from the _Catch.

    This analysis is straighforward but won't work for try blocks nested within a catch clause.

    A real analysis solution for this would require a more powerful data flow analysis with exception handling integrated within it. It's possible we will provide something like this in a future version of FxCop.

    Friday, December 30, 2005 9:00 PM

All replies

  • This code might help you. This has been written in FxCop1.30

    public override Problem[] Check (Method method )
    {

    bool isCatchExists = false;
    bool isThrowExists = false;

    //Get all the instrections of the method.
    InstructionList iList = method.Instructions ;

    for(int i=0;i<iList.Length;i++)
    {
    if(iListIdea.OpCode == OpCode._Catch )
    {
    isCatchExists = true;
    }

    //Checking for the existance of the catch block
    if(isCatchExists)
    {
    if(iListIdea.OpCode == OpCode.Throw)
    {
    isThrowExists = true;
    }
    }
    }

    if(isCatchExists )
    {
    //If the call is not made to HandleError method.
    if(!isThrowExists)
    {
    Problems.Add(GetResolution(method.FullName));
    }
    }
    return ( Problems.AsArray() );

    }
    Wednesday, December 28, 2005 11:37 AM
  • The easiest way to write a check would look like this:

    1) foreach over all Method.Instructions

    2) On encountering an instruction where Instruction.OpCode == OpCode._Catch, do a forward seek until you encounter an OpCode._EndHandler instruction for which the Instruction.Value matches the opening _Catch instruction. If you encounter a throw instruction, stop seeking and continue processing from the _Catch.

    This analysis is straighforward but won't work for try blocks nested within a catch clause.

    A real analysis solution for this would require a more powerful data flow analysis with exception handling integrated within it. It's possible we will provide something like this in a future version of FxCop.

    Friday, December 30, 2005 9:00 PM