Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# catch(FileNotFoundException) and CA1031

So this code triggers CA1031.

try
{
    // logic
}
catch (FileNotFoundException) // exception type
{
    // handle error
}

While this one does not:

try
{
    // logic
}
catch (FileNotFoundException ex) // exception var
{
    // handle error
}

Because the exception type is meaningful, I don't need the ex in the first example. But it's not a a general exception type. It's not IOException or Exception. So why does it still trigger the CA1031?

So is there a difference between catch(FileNotFoundException) and catch(FileNotFoundException ex) outside the fact that I don't capture exception info?

like image 516
CodeAngry Avatar asked Oct 31 '19 17:10

CodeAngry


Video Answer


1 Answers

So this code triggers CA1031

try
{
    // logic
}
catch (FileNotFoundException) // exception type
{
    // handle error
}

This occurs because a "general exception such as System.Exception or System.SystemException is caught in a catch statement, or a general catch clause such as catch() is used". To fix it, assign it and handle the error and or rethrow the general exception for it to be handled further up.

Upon further investigation, it seems this used to be an bug, you can see more here; it was a Roslyn issue for FxCop.

To Fix: Just update the latest FxCop analyzers package and it should go way.

NuGet:

 Install-Package Microsoft.CodeAnalysis.FxCopAnalyzers -Version 2.9.7

References: CA1031

like image 185
Trevor Avatar answered Sep 29 '22 17:09

Trevor