Suppress warning on unused exception variable in C#

C#Visual Studio-2008Exception Handling

C# 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 XYZExceptions. 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#

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJordiView Question on Stackoverflow
Solution 1 - C#JanView Answer on Stackoverflow
Solution 2 - C#Tim LloydView Answer on Stackoverflow
Solution 3 - C#AdamView Answer on Stackoverflow
Solution 4 - C#Andy A.View Answer on Stackoverflow