80

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.

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Wassim AZIRAR
  • 10,823
  • 38
  • 121
  • 174

7 Answers7

157
  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.
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Jalal Said
  • 15,906
  • 7
  • 45
  • 68
43

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();
}
Khepri
  • 9,547
  • 5
  • 45
  • 61
29

You can simply write:

catch (AmbiguousMatchException)

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

fparadis2
  • 913
  • 7
  • 12
  • +1 since it resolves the warning! not explained in [MSDN](http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(RETHROWTOPRESERVESTACKDETAILS);k(TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV4.0%22);k(DevLang-CSHARP)&rd=true). – Ram May 17 '13 at 12:33
3

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);
Neil
  • 5,179
  • 8
  • 48
  • 87
2

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.

Brad
  • 159,648
  • 54
  • 349
  • 530
1

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
}
Ray Chakrit
  • 404
  • 5
  • 7
0

Just ran into this, where the exception was used based upon compiler variables...

Anyway, my solution was:

 _ = MyException;

Picks it up as used, acknowledges that it isn't really being used.

jmoreno
  • 12,752
  • 4
  • 60
  • 91