使用代码分析来分析托管代码质量 之 CA2200

vs的代码分析功能:vs菜单 “生成”下面有“对解决方案运行代码分析 Alt+F11”和“对[当前项目]运行代码分析”2个子菜单。

使用这个功能,可以对托管代码运行代码分析,发现代码中的缺陷和潜在问题,据此分析结果我们可以对程序做相应优化调整。

常见的分析类别有:

  • Usage---使用冲突
  • Security---如不安全的数据访问,sql注入
  • Design----设计问题

 来看几个代码分析结果。

  

下面针对分析结果“CA2200 再次引发以保留堆栈详细信息”做个小述。

具体可见msdn:《CA2200: Rethrow to preserve stack details

当一个异常被抛出时,这个异常通常包含其详细的堆栈跟踪信息。一个完整的堆栈跟踪是方法调用层次结构的列表,从引发该异常的方法开始,一直到捕获到该异常的方法为止。

CA2200是什么?

CA2200可不是国航航班哦~

 CA2200是一个规则,这个规则是说,你如果在代码中捕获了某异常,并且在catch里(做相应处理比如记录日志后)又把这个异常实例throw出去重新引发该异常,那么,这种情况下,堆栈跟踪是从throw语句开始的,而不是从引发该异常的原始代码行启动的。这将不利于我们对一些问题的排障。所以,CA2200建议我们,若要保留该异常的原始堆栈跟踪信息,就要在使用 throw 语句时不要指定该异常。

看下面的demo示例:

 1 using Microsoft.VisualStudio.TestTools.UnitTesting;
 2 using System;
 3 
 4 namespace UsageLibrary
 5 {
 6     [TestClass]
 7     public class TestsRethrow
 8     {
 9         [TestMethod]
10         public void CatchException()
11         {
12             try
13             {
14                 CatchAndRethrowExplicitly();
15             }
16             catch (ArithmeticException e)
17             {
18                 Console.WriteLine("Explicitly specified:{0}{1}",
19                    Environment.NewLine, e.StackTrace);
20             }
21 
22             try
23             {
24                 CatchAndRethrowImplicitly();
25             }
26             catch (ArithmeticException e)
27             {
28                 Console.WriteLine("Implicitly specified:{0}{1}",
29                    Environment.NewLine, e.StackTrace);
30             }
31         }
32 
33         void CatchAndRethrowExplicitly()
34         {
35             try
36             {
37                 ThrowException();
38             }
39             catch (ArithmeticException e)
40             {
41                 // Violates the rule.
42                 throw e;
43             }
44         }
45 
46         void CatchAndRethrowImplicitly()
47         {
48             try
49             {
50                 ThrowException();
51             }
52             catch (ArithmeticException e)
53             {
54                 // Satisfies the rule.
55                 throw;
56             }
57         }
58 
59         void ThrowException()
60         {
61             throw new ArithmeticException("illegal expression");
62         }
63     }
64 }

执行代码,运行结果为:

 

原文地址:https://www.cnblogs.com/buguge/p/6278939.html