How do I detect and correct usless try catch blocks? [closed]

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-07 16:37:50

问题


I've started using the .Net Complier Platform (Roslyn) to assist with enforcing coding standards.

One issue I'm struggling with is discovering and catching useless try...catch blocks.

For example:

// Would like to have this detected and offer to remove the try...catch
try
{
    // Do some work
}
catch(Exception ex)
{
    throw ex;
}

It would be good to also detect the fact that the code is using throw ex; rather than just throw; such as:

try
{
    // So some work
}
catch(Exception ex)
{
    // Log the error or anything to manage the exception
    throw ex;  // <-- how to detect and offer a fix for this
}

回答1:


It sort of depends on what you consider a "useless try-catch". I've assumed you mean catch statements that do no other work except throwing the exception.

Given a C# syntax tree with the code you've provided, you might want to find all the syntax nodes of type CatchClauseSyntax.

You could then look within each for StatementSyntax that is not of type ThrowStatementSyntax. If there are any statements that are not throw, we assume real work is being done here.

For example:

var tree = CSharpSyntaxTree.ParseText(@"
public class MyClass {
public void Method()
{
    try { }
    catch(Exception e)
    {
        //useless
        throw e;
    }
    try {  }
    catch(Exception e)
    {
        //Some work
        int aVariable = 4;
        throw e;
    }
}
}
");

//Finds all catch clauses
var catchClauses = tree.GetRoot().DescendantNodesAndSelf().OfType<CatchClauseSyntax>();
//Look at the catch blocks
var catchBlocks = catchClauses.Select(n => n.DescendantNodes().OfType<BlockSyntax>().First());
//Filter out the clauses where statements all are only throw statements
var uselessClauses = catchBlocks.Where(n => n.Statements.All(m => m is ThrowStatementSyntax));


来源:https://stackoverflow.com/questions/24257437/how-do-i-detect-and-correct-usless-try-catch-blocks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!