C#: Find all empty catch blocks

2019-01-31 23:50发布

I am reviewing some code.

I have notice some empty catch blocks. Not a good idea since somethings do not work and you cannot see why.

Is there an easy way to find all empty try catch blocks in a solution?

8条回答
唯我独甜
2楼-- · 2019-02-01 00:08

Thanks to Stefan for the Regex suggestion. I found that the suggested regex does not find catch blocks where the exception is not specified, ie:

catch { }

I tweaked Stefan's slightly to make the exception brace optional:

catch:b*(\([^)]*\))*:b*\{:b*\}
查看更多
\"骚年 ilove
3楼-- · 2019-02-01 00:09

Use use the global find dialog, turn on regular expressions and then search for:

catch:b*\([^)]*\):b*\{:b*\}
查看更多
乱世女痞
4楼-- · 2019-02-01 00:09

Press Ctrl + Shift + F. Expand Find options. Check Use Regular Expressions Paste this regex.

catch\s*(\(\s*Exception(\s*\w+)?\))?\s*\{\s*\}
查看更多
仙女界的扛把子
5楼-- · 2019-02-01 00:24

Further expanded the three solutions above to include clauses where the curly brackets aren't on the same line as the catch and where the catch clause contains only single line quotes:

catch:b*(\([^)]*\))*:b*[ \n\r\t]*\{:b*([ \n\r\t.]|(\/*[^]*\/)|(//.*$))*\}
查看更多
疯言疯语
6楼-- · 2019-02-01 00:27

FxCop will find them along with many other potential issues.

查看更多
时光不老,我们不散
7楼-- · 2019-02-01 00:28

Here is a regular expression that finds also catch blocks with only comments inside :

catch:b*\([^)]*\)[:b\n]*\{([:b\n]|(\/\*[^*]*\*\/)|(//[^\n]*))*\}
查看更多
登录 后发表回答