84

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.

0

7 Answers 7

163
  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.
Sign up to request clarification or add additional context in comments.

7 Comments

A list of all compiler errors and warnings are available at the MSDN
The solution given by @fparadis2 is better since not advisable to supress warnings when we can fix it
@dasariramacharanprasad that was my first suggestion, re-read my answer ;)
solution #2 is not a solution, it is a mask.
But it is a sharp one isn't it :)
|
46

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();
}

Comments

33

You can simply write:

catch (AmbiguousMatchException)

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

1 Comment

+1 since it resolves the warning! not explained in MSDN.
4

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);

Comments

3

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.

Comments

2

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
}

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.