Suppress warning on unused exception variable in C#
C#Visual Studio-2008Exception HandlingC# Problem Overview
I have this code:
try {
someMethod();
} catch (XYZException e) {
// do something without using e
}
Doing this will give me a warning about declaring but never using e
, which I hate. However, I also don't want to use a catch
clause without that variable, because then it will catch all exceptions, not just XYZException
s. This seems like a fairly often occurring pattern. I know I can use #pragma warning disable 0168
to suppress the warning, but I don't really find that a very elegant solution. Is there a better way?
C# Solutions
Solution 1 - C#
Define the catch clause without the exception variable as follows:
try {
someMethod();
} catch (XYZException) {
// do something without using e
}
Solution 2 - C#
Define the catch clause without the exception variable as follows:
try {
someMethod();
} catch (XYZException) {
// do not state e in catch clause
}
Solution 3 - C#
Another option is to use
try
{
someMethod();
}
#pragma warning disable 0168
catch (XYZException e)
#pragma warning restore 0168
{
// do not state e in catch clause
}
This is useful in visual studio 2015 because it doesn't have a way to see the exception by default when debugging with a breakpoint on the catch.
Solution 4 - C#
Use the System.Diagnostics.CodeAnalysis.SuppressMessage
attribute.
[visit Microsoft][link_to_ms]
[link_to_ms]: https://docs.microsoft.com/en-gb/dotnet/api/system.diagnostics.codeanalysis.suppressmessageattribute?view=netframework-4.8 "https://docs.microsoft.com/en-gb/dotnet/api/system.diagnostics.codeanalysis.suppressmessageattribute?view=netframework-4.8"