C#: Find all empty catch blocks

Viewed 5399

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?

10 Answers

Expanding on @bobah75 's answer, it wouldn't recognize this line

catch (System.Data.Entity.Core.EntityException ex)
{
}

So to fix that, here is the solution

catch\s*(\(?.+Exception(\s*\w+)?\))?\s*\{\s*([:b\n]|(\/\*[^*]*\*\/)|(//[^\n]*))*\}

you can test it out here

If you can, I would suggest using Sonar Analyzer. You can add it via NuGet manager in Visual Studio.

It will show all unused catch blocks and also show you a tip what do do with it, something in lines of: "Implement or comment why empty."

Also, it will show you a lot more of possible code issues.

catch\s*((?.+Exception(\s*\w+)?))?\s*{\s*([:b\n]|(/*[^]*/)|(//[^\n]))}

Visual Studio 2022. Only This expression is actually working.

Related