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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With