c# - 如何确定给定方法可以抛出哪些异常?

标签 c# exception error-handling

我的问题真的和这个一样"Finding out what exceptions a method might throw in C#" .但是,我真的很想知道是否有人知道一种方法来确定给定方法可能抛出的所有异常的堆栈。我希望有一个工具或实用程序可以在编译时或通过像 FxCop、StyleCop 或 NCover 这样的反射来分析代码。我在运行时不需要这些信息,我只是想确保我们捕获异常并将它们正确地记录到输出代码中。

我们目前正在捕获已知的异常并记录所有通配符。这确实很有效;但是,我只是希望有人使用过或知道可以发现此信息的工具。

最佳答案

根据我之前的回答,我成功地创建了一个基本的异常查找器。它利用基于反射的 ILReader类,可用here在 Haibo Luo 的 MSDN 博客上。 (只需添加对项目的引用即可。)

更新:

  1. 现在处理局部变量和堆栈。
    • 正确检测从方法调用或字段返回并随后抛出的异常。
    • 现在可以完全适本地处理堆栈推送/弹出。

这是完整的代码。您只想使用 GetAllExceptions(MethodBase)方法作为扩展或静态方法。

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using ClrTest.Reflection;

public static class ExceptionAnalyser
{
    public static ReadOnlyCollection<Type> GetAllExceptions(this MethodBase method)
    {
        var exceptionTypes = new HashSet<Type>();
        var visitedMethods = new HashSet<MethodBase>();
        var localVars = new Type[ushort.MaxValue];
        var stack = new Stack<Type>();
        GetAllExceptions(method, exceptionTypes, visitedMethods, localVars, stack, 0);

        return exceptionTypes.ToList().AsReadOnly();
    }

    public static void GetAllExceptions(MethodBase method, HashSet<Type> exceptionTypes,
        HashSet<MethodBase> visitedMethods, Type[] localVars, Stack<Type> stack, int depth)
    {
        var ilReader = new ILReader(method);
        var allInstructions = ilReader.ToArray();

        ILInstruction instruction;
        for (int i = 0; i < allInstructions.Length; i++)
        {
            instruction = allInstructions[i];

            if (instruction is InlineMethodInstruction)
            {
                var methodInstruction = (InlineMethodInstruction)instruction;

                if (!visitedMethods.Contains(methodInstruction.Method))
                {
                    visitedMethods.Add(methodInstruction.Method);
                    GetAllExceptions(methodInstruction.Method, exceptionTypes, visitedMethods,
                        localVars, stack, depth + 1);
                }

                var curMethod = methodInstruction.Method;
                if (curMethod is ConstructorInfo)
                    stack.Push(((ConstructorInfo)curMethod).DeclaringType);
                else if (method is MethodInfo)
                    stack.Push(((MethodInfo)curMethod).ReturnParameter.ParameterType);
            }
            else if (instruction is InlineFieldInstruction)
            {
                var fieldInstruction = (InlineFieldInstruction)instruction;
                stack.Push(fieldInstruction.Field.FieldType);
            }
            else if (instruction is ShortInlineBrTargetInstruction)
            {
            }
            else if (instruction is InlineBrTargetInstruction)
            {
            }
            else
            {
                switch (instruction.OpCode.Value)
                {
                    // ld*
                    case 0x06:
                        stack.Push(localVars[0]);
                        break;
                    case 0x07:
                        stack.Push(localVars[1]);
                        break;
                    case 0x08:
                        stack.Push(localVars[2]);
                        break;
                    case 0x09:
                        stack.Push(localVars[3]);
                        break;
                    case 0x11:
                        {
                            var index = (ushort)allInstructions[i + 1].OpCode.Value;
                            stack.Push(localVars[index]);
                            break;
                        }
                    // st*
                    case 0x0A:
                        localVars[0] = stack.Pop();
                        break;
                    case 0x0B:
                        localVars[1] = stack.Pop();
                        break;
                    case 0x0C:
                        localVars[2] = stack.Pop();
                        break;
                    case 0x0D:
                        localVars[3] = stack.Pop();
                        break;
                    case 0x13:
                        {
                            var index = (ushort)allInstructions[i + 1].OpCode.Value;
                            localVars[index] = stack.Pop();
                            break;
                        }
                    // throw
                    case 0x7A:
                        if (stack.Peek() == null)
                            break;
                        if (!typeof(Exception).IsAssignableFrom(stack.Peek()))
                        {
                            //var ops = allInstructions.Select(f => f.OpCode).ToArray();
                            //break;
                        }
                        exceptionTypes.Add(stack.Pop());
                        break;
                    default:
                        switch (instruction.OpCode.StackBehaviourPop)
                        {
                            case StackBehaviour.Pop0:
                                break;
                            case StackBehaviour.Pop1:
                            case StackBehaviour.Popi:
                            case StackBehaviour.Popref:
                            case StackBehaviour.Varpop:
                                stack.Pop();
                                break;
                            case StackBehaviour.Pop1_pop1:
                            case StackBehaviour.Popi_pop1:
                            case StackBehaviour.Popi_popi:
                            case StackBehaviour.Popi_popi8:
                            case StackBehaviour.Popi_popr4:
                            case StackBehaviour.Popi_popr8:
                            case StackBehaviour.Popref_pop1:
                            case StackBehaviour.Popref_popi:
                                stack.Pop();
                                stack.Pop();
                                break;
                            case StackBehaviour.Popref_popi_pop1:
                            case StackBehaviour.Popref_popi_popi:
                            case StackBehaviour.Popref_popi_popi8:
                            case StackBehaviour.Popref_popi_popr4:
                            case StackBehaviour.Popref_popi_popr8:
                            case StackBehaviour.Popref_popi_popref:
                                stack.Pop();
                                stack.Pop();
                                stack.Pop();
                                break;
                        }

                        switch (instruction.OpCode.StackBehaviourPush)
                        {
                            case StackBehaviour.Push0:
                                break;
                            case StackBehaviour.Push1:
                            case StackBehaviour.Pushi:
                            case StackBehaviour.Pushi8:
                            case StackBehaviour.Pushr4:
                            case StackBehaviour.Pushr8:
                            case StackBehaviour.Pushref:
                            case StackBehaviour.Varpush:
                                stack.Push(null);
                                break;
                            case StackBehaviour.Push1_push1:
                                stack.Push(null);
                                stack.Push(null);
                                break;
                        }

                        break;
                }
            }
        }
    }
}

总而言之,该算法通过读取 CIL 指令(以及跟踪已访问的方法),递归地枚举(深度优先)在指定方法中调用的任何方法。它维护一个集合列表,可以使用 HashSet<T> 抛出这些集合。对象,最后返回。它还维护一个局部变量数组和一个堆栈,以便跟踪在创建后未立即抛出的异常。

当然,这段代码在其当前状态下并非万无一失。我需要做一些改进才能使其健壮,即:

  1. 检测不是使用异常构造函数直接抛出的异常。 (即异常是从局部变量或方法调用中检索到的。)
  2. 支持异常从堆栈弹出然后推回。
  3. 添加流量控制检测。处理任何抛出的异常的 Try-catch block 应该从列表中删除适当的异常,除非 rethrow检测到指令。

除此之外,我相信代码是合理完整的。在我弄清楚如何进行流量控制检测之前,可能需要进行更多调查(尽管我相信我现在可以看到它是如何在 IL 级别运行的)。

如果要创建一个功能齐全的“异常分析器”,这些函数可能会变成一个完整的库,但希望这至少能为这样的工具提供一个良好的起点,如果它的功能还不够好的话当前状态。

无论如何,希望对您有所帮助!

关于c# - 如何确定给定方法可以抛出哪些异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/986180/

相关文章:

c# - 打开预先存在的 Excel 文件

c# - 小巧玲珑的彩虹 MissingMethodException

c# - 有没有办法我们可以动态添加伪元素 css 作为内联 css

javascript - 在 JavaScript 中重新抛出异常有什么意义?

java - setTitle 方法中的异常

python - 多案例异常处理python

c# - 为 C# 契约类创建 Resharper 命名风格

c# - 插入多条记录时 Entity Framework 外键问题?

powershell - 检查网址以获取特定文本,如果匹配则下载,如果名称无法解析则继续下一个

python - AWS Boto3 s3 put_object错误处理/测试