A System.Collections.Generic.Dictionary
is throwing KeyNotFoundException
, but I can't see which key is supposedly missing. How do I determine this?
Custom exception:
class WellknownKeyNotFoundException : KeyNotFoundException
{
public WellknownKeyNotFoundException(object key, string message)
: this(key, message, null) { }
public WellknownKeyNotFoundException(object key, string message, Exception innerException)
: base(message, innerException)
{
this.Key = key;
}
public object Key { get; private set; }
}
Handy extension method:
public TValue GetValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
{
try
{
return dic[key];
}
catch (KeyNotFoundException ex)
{
throw new WellknownKeyNotFoundException((object)key, ex.InnerException);
}
}
Usage:
var foo = new Foo();
var bar = new Bar();
IDictionary<Foo, Bar> dic = new Dictinary<Foo, Bar>
{
{ foo, bar }
};
try
{
dic.GetValue(foo);
}
catch (WellknownKeyNotFoundException ex)
{
var key = (Foo)ex.Key;
Assert.AreEqual(foo, key); // should be
}