How can I determine which exceptions can be thrown by a given method?

前端 未结 9 984
感情败类
感情败类 2020-11-30 22:41

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 deter

9条回答
  •  情深已故
    2020-11-30 23:01

    I'm very doubtful there is any (at least straightforward) way to do this in C#. Saying that, I do have an idea that may work, so read on please...

    Firstly, it's worth noting that doing a brute-force search using a huge number of permutations of arguments clearly is not feasible. Even having prior knowledge of parameter types (which I don't believe is desirable in your situation), the task essentially reduces to the halting problem in the general case, since you don't know the function will terminate given certian parameters. Ideally, exceptions should stop this, but it isn't always the case of course.

    Now, perhaps the most reliable method is to analyse the source code (or more realistically CIL code) itself to see which exceptions might be thrown. This I believe may actually be workable. A simple algorithm might go something like:

    1. Do a depth-first or breadth-first search of the given method. Find all methods/properties that are called anywhere within the method body, and recurse on them.
    2. For each block of CIL code in tree of methods/propreties, examine code for any exceptions that might be thrown, and add to a list.

    This would even allow you to get detailed information about the exceptions, such as whether they are thrown directly by the called method, or deeper in the call stack, or even the exception messages themselves. Anyway, I'll consider giving an implementation of this a try later this afternoon, so I'll let you know how feasible the idea is then.

提交回复
热议问题