In a Visual Studio 2010 C# Project, how do I find out if any method is written without having a try-catch block?

Sometimes as a code reviewer, its hard to search function/methods which are not properly written according to code standards esp: without a try-catch block.

I know that the Find option in Visual Studio supports regular expressions. But what's the regular expression that could perform this job smartly?

有帮助吗?

解决方案

Edit (putting the direct answer first): It would actually be easy to use Assembly.ReflectionOnlyLoadFrom, then enumerate the types, and the methods of those types, then for each method body examine the ExceptionHandlingClauses.

Commentary follows:

Red Gate used to offer the Exception Hunter tool for tracking down possible exception issues. As mentioned on that page, it's been shown that the specific task you have requested (broad searches for any unhandled exception) does not lead to higher quality software even with assistance of automated analysis tools.

If I needed to find a list of all methods without a protected region, I could simply use one of my experimental assembly loaders (written with relative ease according to ECMA-335) and examine the metadata as described in ECMA-335, Partition II, §25.4.5 and §25.4.6 (much easier to use the first part of this answer). If I needed to find a list of these methods for the purpose of adding a protected region to each of them to conform to a coding standard, I would report back that they need to find another developer to do that because I refuse to knowingly and intentionally degrade the quality of software I work on.

其他提示

If you have access to Visual Studio 2012 (the beta is a free download!), you can use the Search For Code Clones option.

Normally this will search your whole solution but you can scope it to a specific piece of code. You can easily use this to find all code where, for example, a disposable object is used. Then you can chek if a using statement is used everywhere.

This same mechanism can be used to check if a certain piece of code is used in a try/catch block.

Here is some MSDN documentation.

I think you could use Roslyn to process the code and find which methods have or don't have try/catch blocks by examining the expression tree.

I would not advise you to use Regex to do that. You'd have to write a quite complex script that would be a state machine based on when a method block starts and when it finishes, and then inspecting whether are try-catches in there.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top