The variable 'MyException' is declared but never used

C#.NetExceptionFrameworksAmbiguity

C# Problem Overview


I need to clear this warning :

try
{
    doSomething()
}
catch (AmbiguousMatchException MyException)
{
    doSomethingElse()
}

The complier is telling me : >The variable 'MyException' is declared but never used

How can I fix this.

C# Solutions


Solution 1 - C#

  1. You can remove it like this:

    try
    {
        doSomething()
    }
    catch (AmbiguousMatchException)
    {
        doSomethingElse()
    }
    
  2. Use warning disable like this:

    try
    {
        doSomething()
    }
    #pragma warning disable 0168
    catch (AmbiguousMatchException exception)
    #pragma warning restore 0168
    {
        doSomethingElse()
    }
    

Other familiar warning disable

#pragma warning disable 0168 // variable declared but not used.
#pragma warning disable 0219 // variable assigned but not used.
#pragma warning disable 0414 // private field assigned but not used.

Solution 2 - C#

You declare a name for the exception, MyException, but you never do anything with it. Since it's not used, the compiler points it out.

You can simply remove the name.

catch(AmbiguousMatchException)
{
   doSomethingElse();
}

Solution 3 - C#

You can simply write:

catch (AmbiguousMatchException)

and omit the exception name if you won't be using it in the catch clause.

Solution 4 - C#

You could write the exception out to a log if you've got one running. Might be useful for tracking down any problems.

Log.Write("AmbiguousMatchException: {0}", MyException.Message);

Solution 5 - C#

The trouble is, you aren't using your variable MyException anywhere. It gets declared, but isn't used. This isn't a problem... just the compiler giving you a hint in case you intended to use it.

Solution 6 - C#

but never used means that you should use it after catch() such as writing its value to console, then this warning message will disappear.

catch (AmbiguousMatchException MyException)
{
    Console.WriteLine(MyException); // use it here
}

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
QuestionWassim AZIRARView Question on Stackoverflow
Solution 1 - C#Jalal SaidView Answer on Stackoverflow
Solution 2 - C#KhepriView Answer on Stackoverflow
Solution 3 - C#fparadis2View Answer on Stackoverflow
Solution 4 - C#NeilView Answer on Stackoverflow
Solution 5 - C#BradView Answer on Stackoverflow
Solution 6 - C#Ray ChakritView Answer on Stackoverflow