如何检测和纠正无用的try catch块?

我已经开始使用.Net Complier Platform(Roslyn)来协助执行编码标准。

我正在努力解决的一个问题是发现并捕捉无用的try...catch块。

例如:

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

最好还能检测到代码使用throw ex;的事实throw ex; 而不仅仅是throw; 如:

 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 } 

这有点取决于你认为“无用的试捕”。 我假设你的意思是除了抛出exception之外没有其他工作的catch语句。

给定带有您提供的代码的C#语法树,您可能希望找到CatchClauseSyntax类型的所有语法节点。

然后,您可以在每个内部查找不属于ThrowStatementSyntax类型的ThrowStatementSyntax 。 如果有任何未抛出的陈述,我们假设这里正在进行实际工作。

例如:

 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(); //Look at the catch blocks var catchBlocks = catchClauses.Select(n => n.DescendantNodes().OfType().First()); //Filter out the clauses where statements all are only throw statements var uselessClauses = catchBlocks.Where(n => n.Statements.All(m => m is ThrowStatementSyntax));