如何确定给定方法可以抛出哪些异常? [英] How can I determine which exceptions can be thrown by a given method?

查看:177
本文介绍了如何确定给定方法可以抛出哪些异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与此相同找出方法可能在C#中抛出什么异常。然而,我真的想知道是否有人知道一种方法来确定给定方法可能抛出的所有异常的堆栈。我希望有一个工具或实用程序,我可以在编译时或通过像FxCop,StyleCop或NCover这样的反射来分析代码。我在运行时不需要这些信息,我只是想确保我们正在捕获异常并正确地记录在代码中。

My question is really the same as this one "Finding out what exceptions a method might throw in C#". However, I would really like to know if anyone knows of a way to determine the stack of all the exceptions that may be thrown by a given method. I am hoping for a tool or utility that I can analyze code at compile time or through reflection like FxCop, StyleCop, or NCover. I do not need this information at run time I just want to make sure we are trapping exceptions and logging them correctly in out code.

我们正在捕获我们所知道的并记录所有通配符的异常。这样做很好但是,我只是希望有人使用或知道可以发现这些信息的工具。

We are currently trapping the exceptions that we know about and logging all the wild cards. This does work well; however, i was just hoping someone has used or knows of a tool that can discover this information.

推荐答案

跟随我以前的回答,我设法创建了一个基本的异常查找器。它使用基于反射的 ILReader 类,可用这里在海博罗的MSDN博客。 (只需添加项目的引用。)

Following up to my previous answer, I've managed to create a basic exception finder. It utilises a reflection-based ILReader class, available here on Haibo Luo's MSDN blog. (Just add a reference to the project.)

更新:


  1. 现在处理局部变量和堆栈。


    • 正确检测从方法调用或字段返回的异常并稍后抛出。

    • 现在可以完全处理堆栈推/

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

Here is the code, in full. You simply want to use the GetAllExceptions(MethodBase) method either as an extension or static method.

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


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

To summarise, this algorithm recursively enumerates (depth-first) any methods called within the specified one, by reading the CIL instructions (as well as keeping track of methods already visited). It maintains a single list of collections that can be thrown using a HashSet<T> object, which is returned at the end. It additionally maintains an array of local variables and a stack, in order to keep track of exceptions that aren't thrown immediately after they are created.

当然,这段代码在当前状态下不是绝对的。有一些改进,我需要使其强大,即:

Of course, this code isn't infallible in it's current state. There are a few improvements that I need to make for it to be robust, namely:


  1. 检测未抛出的异常直接使用异常构造函数。 (即从本地变量或方法调用中检索异常。)

  2. 支持从堆栈弹出的异常,然后稍后重新启动。

  3. 添加流量控制检测。除非检测到 rethrow 指令,否则处理任何抛出的异常的Try-catch块应该从列表中删除适当的异常。

  1. Detect exceptions that aren't thrown directly using an exception constructor. (i.e. The exception is retrieved from a local variable or a method call.)
  2. Support exceptions popped off the stack then later pushed back on.
  3. Add flow-control detection. Try-catch blocks that handle any thrown exception should remove the appropiate exception from the list, unless a rethrow instruction is detected.

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

Apart from that, I believe the code is reasonably complete. It may take a bit more investigation before I figure out exactly how to do the flow-control detection (though I believe I can see how it operates at the IL-level now).

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

These functions could probably be turned into an entire library if one was to create a full-featured "exception analyser", but hopefully this will at least provide a sound starting point for such a tool, if not already good enough in its current state.

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

Anyway, hope that helps!

这篇关于如何确定给定方法可以抛出哪些异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆