Csharp/C#教程:如何检测和纠正无用的try catch块?分享


如何检测和纠正无用的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 。 如果有任何未抛出的陈述,我们假设这里正在进行实际工作。

例如:

上述就是C#学习教程:如何检测和纠正无用的try catch块?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 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)); 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/988676.html

(0)
上一篇 2021年12月24日
下一篇 2021年12月24日

精彩推荐